我尝试用谷歌搜索我的问题,但考虑到标题,我发现很难正确表达,所以我找不到任何东西。所以我决定在这里问:为什么会编译?
#include <cstdio>
class Test
{
public:
Test(int param = 42)
{
printf("ctor %d\n", param);
_data = param;
}
private:
int _data = 0;
};
class Test2
{
// wtf? v is not yet declared
Test t{ v };
int v = 333;
};
int main()
{
Test2 t2;
// This doesn't compile though.
// Test t{ v };
// int v = 333;
printf("don't optimize 0x%X\n", &t2);
return 0;
}
我预计编译器会发出“未声明的变量 v”或其他错误。
v 只是 Test2 类的成员。作为成员,在您显示的示例中使用之前不需要声明它。它也可以在 Test2 的成员函数中使用,而无需在这些函数之前声明。