gpt4 book ai didi

c++ - 继承构造函数

转载 作者:IT老高 更新时间:2023-10-28 11:27:46 25 4
gpt4 key购买 nike

为什么会有这段代码:

class A
{
public:
explicit A(int x) {}
};

class B: public A
{
};

int main(void)
{
B *b = new B(5);
delete b;
}

导致这些错误:

main.cpp: In function ‘int main()’:main.cpp:13: error: no matching function for call to ‘B::B(int)’main.cpp:8: note: candidates are: B::B()main.cpp:8: note:                 B::B(const B&)

B不应该继承A的构造函数吗?

(这是使用 gcc)

最佳答案

如果您的编译器支持 C++11 标准,则存在使用 using 的构造函数继承(双关语)。更多信息见 Wikipedia C++11 article .你写:

class A
{
public:
explicit A(int x) {}
};

class B: public A
{
using A::A;
};

这是全有或全无 - 你不能只继承一些构造函数,如果你写这个,你继承了所有的。要仅继承选定的那些,您需要手动编写各个构造函数并根据需要从它们调用基本构造函数。

历史上构造函数不能在 C++03 标准中被继承。您需要通过自己调用基本实现来一一手动继承它们。


对于模板化的基类,引用这个例子:

using std::vector;

template<class T>
class my_vector : public vector<T> {
public:
using vector<T>::vector; ///Takes all vector's constructors
/* */
};

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

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