c++ - C++中的构造函数调用

标签 c++ class constructor

只有在创建对象后,内存才会分配给类中的变量……对吧? 那么,如果该类包含一个变量,该变量是另一个类的对象并且该变量具有构造函数怎么办?

class Wand
{
    mouse mouseEmu(0,0);
    QCursor pt;
};

mouseEmuQCursor 是两个类...

什么时候调用mouseEmu的构造函数,什么时候调用pt的默认构造函数?

如果我们指定一个,是否需要调用参数化构造函数?

最佳答案

新问题(或旧问题,取决于您到达的时间)

class Wand
{
    mouse mouseEmu(0,0);
             //   ^^^^^^  This bit is illegal.
             //           Remove it here. You specify the parameters
             //           Passed to members in the constructor.
    QCursor pt;
};

你想要的是:

class Wand
{
    Ward(): mouseEmu(0,0) {}
    mouse mouseEmu;
    QCursor pt;
};

编辑:

根据被更改为非法之前的问题回答。

如果您不提供构造函数,那么编译器会为您植入一个隐式默认构造函数:

Wand::Wand()
  : mouseEmu()
  , pt()
{}

当你创建一个 Wand 对象时。它将自动创建和初始化其成员(mouseEmu 和 pt)作为 Wand 对象构造的一部分。调用它们的构造函数(按照类中声明的顺序)。

注意:如果你自己定义构造函数。但是不要显式调用成员的构造函数,然后隐式调用成员的默认构造函数(成员的构造顺序始终声明的顺序。

 // Example:
 // If you did:

 class Wand
 {
      Wand(int x) : mouseEmu(0,x) {}

      // The above will generate this logical code.
      Wand(int x) : mouseEmu(0,x), pt() {}
 }

关于c++ - C++中的构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10260589/

相关文章:

c++ - 非静态数据成员 c++ 的无效使用

C++:在派生类构造函数中调用基类赋值运算符的形式不正确?

c++ - 如何在 Qt 中为 QTabWidget 设置背景图片

c++ - 在 OSX Yosemite 上使用 Accelerate Framework 进行编译

c++ - 为什么一个类的静态成员对于所有对象都是一样的?

c# - c#中的动态类构造函数

java - 为什么如果我的文件名和公共(public)类名不同,我会收到编译错误?

c++ - 用于大型 C++ 项目的良好、简单的配置库?

c++ - 何时使用并行计数 - 当内存有问题时使用 MIT HAKMEM 进行位计数?

python 类方法 : parameter as class variables pros and cons