gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:46 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com