gpt4 book ai didi

c++ - 构造函数可以在 C++ 中调用另一个类的构造函数吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:52 25 4
gpt4 key购买 nike

class A {
public:
A(int v) {
_val = v;
}

private:
int _val;
};

class B {
public:
B(int v) {
a = A(v); // i think this is the key point
}

private:
A a;
};

int main() {
B b(10);

return 0;
}

编译器说:

test.cpp: In constructor ‘B::B(int)’:
test.cpp:15: error: no matching function for call to ‘A::A()’
test.cpp:5: note: candidates are: A::A(int)
test.cpp:3: note: A::A(const A&)

我学过Java,不知道用C++怎么处理这个。搜索了几天,请告诉我 C++ 可以做到这一点吗?

最佳答案

您需要使用 Member Initialization List

B(int v):a(v)
{
}

与:

B(int v) 
{
a = A(v); // i think this is the key point
}

a 正在被分配 一个值,而不是被初始化(这是你想要的),一旦构造函数的主体开始 {,它的所有成员都已经构造完成。

为什么会出现错误?
编译器在构造函数主体 { 开始之前构造 a,编译器使用 A 的无参数构造函数,因为您没有另外告诉它注意 1,由于默认的无参数构造函数不可用,因此会出现错误。

为什么不隐式生成默认的无参数构造函数?
一旦您为您的类提供了any 构造函数,就不会再生成隐式生成的无参数构造函数。您为 A 的构造函数提供了重载,因此没有隐式生成无参数构造函数。

注1
使用成员初始化列表是告诉编译器使用构造函数的特定重载版本而不是默认的无参数构造函数的方法。

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

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