案例1:Main.cpp
class Complex
{
void func()
{
Complex c1; // Creating same class object allowed inside a function. Code builds fine. Why?
}
};
int main()
{
return 0;
}
案例2:Main.cpp
class Complex
{
Complex c1; // Creating same class object not allowed as data member. Build fails because class incomplete
};
int main()
{
return 0;
}
我知道为什么案例 2 无法构建了。但为什么案例1会通过呢? 我读到编译器从上到下逐行编译代码。案例 1 也应该不会因为同样的原因而失败吗?
第二种情况会失败,因为对象在内存中的大小必须是有限的。类的成员函数没有理由不能拥有相同类型的本地对象。如果对象的大小是有限的(并非荒谬),那么当调用成员函数时,没有理由不能在堆栈上创建它。
该对象仅在调用
Complex::func
时创建。