我观察到奇怪的行为在g ++ 4.6.3。当通过调用类的构造函数创建一个临时File(arg)
编译器选择忽略的arg
存在和解析表达式为File arg;
调用构造函数与成员作为参数分析为变量定义
- 为什么成员名称忽略?
- 标准说的是什么?
- 如何避免它? (不使用新的
{}
语法) - 是否存在相关的编译器警告? (我可以用一个任意字符串ARG,它仍然会默默耕耘)
代码:
#include <iostream>
class File {
public:
explicit File(int val) : m_val(val) { std::cout<<"As desired"<< std::endl; }
File() : m_val(10) { std::cout<< "???"<< std::endl;}
private:
int m_val;
};
class Test {
public:
void RunTest1() { File(m_test_val); }
void RunTest2() { File(this->m_test_val); }
void RunTest3() { File(fhddfkjdh); std::cout<< "Oops undetected typo"<< std::endl; }
private:
int m_test_val;
};
int main()
{
Test t;
t.RunTest1();
t.RunTest2();
t.RunTest3();
return 0;
}
输出:
$ ???
$ As desired
$ Oops undetected typo
只有当您创建对象或使用新位置时,才能直接调用构造函数。 – chris
'fhddfkjdh'如何工作?这是无处定义的,应该会导致编译错误? – RvdK
@PoweRoy,它被视为:'File fdfdsfsda()' – Xyand