当我调用像这样的 Class::Class() 的构造函数时,该操作被认为是简单的函数调用还是暗示其他东西?
struct Point
{
Point()
{
X = 100;
Y = 100;
cout << "Point ctor !\n";
}
int X;
int Y;
};
在main中调用构造函数时,修改X和Y意味着内存中已经存在一个对象,对吗?那么下面的指令到底是什么意思呢?创建一个在堆栈上有两个字段的对象?所以不是简单的函数调用?
int main()
{
Point::Point();
}
看来我的编译器已经过时了:
Point::Point(); // Is illegal.
但是
Point(); // Is fine.
When calling the constructor in the main, modifying X and Y implies that there is an existing object in memory am I right ?
是的。它创建一个临时对象。临时对象在表达式末尾(在本例中为“;”)超出范围,此时它被销毁。
so what does the instruction below really mean ?
这是一种在表达式中创建临时对象的方法。虽然您通常不会费心指定类名。
creating an object with 2 fields in the stack ?
这是未定义的。它创建一个具有两个字段的临时对象(这是一个具有自动存储持续时间的对象)。没有为 C++ 语言定义堆栈这样的东西,所以这个概念没有意义。
so it is not a simple function call ?
是的,调用构造函数来初始化临时对象。
int main()
{
std::cout << Point().Y; // Access the member of the temporary.
}