Syd*_*ius 199 c++ inheritance gcc constructor
为什么这段代码:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
};
int main(void)
{
B *b = new B(5);
delete b;
}
Run Code Online (Sandbox Code Playgroud)
导致这些错误:
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)
Sum*_*uma 357
如果您的编译器支持C++ 11标准,则使用构造函数继承using
(双关语).有关更多信息,请参阅Wikipedia C++ 11文章.你写:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
using A::A;
};
Run Code Online (Sandbox Code Playgroud)
这是全有或全无 - 你不能只继承一些构造函数,如果你写这个,你继承了所有这些.要仅继承选定的构造函数,您需要手动编写各个构造函数,并根据需要从中调用基础构造函数.
历史上,构造函数不能在C++ 03标准中继承.您需要通过自己调用基本实现来逐个手动继承它们.
Avi*_*Avi 85
构造函数不是继承的.它们由子构造函数隐式或显式调用.
编译器创建一个默认构造函数(一个没有参数)和一个默认复制构造函数(一个参数是同一类型的引用).但是如果你想要一个接受int的构造函数,你必须明确地定义它.
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
public:
explicit B(int x) : A(x) { }
};
Run Code Online (Sandbox Code Playgroud)
更新:在C++ 11中,构造函数可以继承.有关详细信息,请参阅Suma的答案.
nen*_*hev 11
这直接来自Bjarne Stroustrup 的页面:
如果您选择这样做,您仍然可以通过在派生类中继承构造函数,在该派生类中定义需要初始化的新成员变量:
struct B1 {
B1(int) { }
};
struct D1 : B1 {
using B1::B1; // implicitly declares D1(int)
int x;
};
void test()
{
D1 d(6); // Oops: d.x is not initialized
D1 e; // error: D1 has no default constructor
}
Run Code Online (Sandbox Code Playgroud)
请注意,使用另一个很棒的 C++11 特性(成员初始化):
int x = 77;
Run Code Online (Sandbox Code Playgroud)
代替
int x;
Run Code Online (Sandbox Code Playgroud)
会解决这个问题
小智 8
如何使用模板函数绑定所有构造函数?
template <class... T> Derived(T... t) : Base(t...) {}
Run Code Online (Sandbox Code Playgroud)
您必须在B中显式定义构造函数并显式调用父级的构造函数.
B(int x) : A(x) { }
Run Code Online (Sandbox Code Playgroud)
要么
B() : A(5) { }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
186488 次 |
最近记录: |