c++ - 将构造函数作为方法调用

标签 c++ constructor

<分区>

当我调用像这样的 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.
}

关于c++ - 将构造函数作为方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37232423/

相关文章:

c++ - 任何可用的实现,如 Loki 的 AssocVector,但具有 Boost 的 Bimap 的功能?

c++ - 相机跟随播放器opengl

java - 如何编写一个构造函数来阻止在某些条件下创建对象

c# - 新表达式需要 ()、[] 或 {} C# 构造函数错误

c++ - 在 C++ 中使用字符串数组多次运行一个函数

c++ - 带参数的构造函数初始化

c++ - Mongocxx 连接错误

c++ - undefined symbol "vtable for ..."和 "typeinfo for..."?

c++ - 使用 TransparentBlt

c# - 使用与创建类不同的泛型类型调用构造函数