继承构造函数 [英] Inheriting constructors

查看:141
本文介绍了继承构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么代码如此:

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

B类:public A
{
};

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

导致以下错误:

 
main.cpp:在函数'int main()':
main.cpp:13:错误:没有匹配函数调用'B :: B '
main.cpp:8:note:candidate are:B :: B()
main.cpp:8:note:B :: B(const B&)

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



(这是使用gcc)

$ b $在C ++ 03中,标准构造函数不能被继承,你需要通过自己调用基类实现手动地逐个继承它们。如果你的编译器支持C ++ 11标准,就有一个构造函数继承。有关详情,请参阅 Wikipedia C ++ 11文章。使用新标准:

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

class B:public A
{
使用A :: A;
};


Why does this code:

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

class B: public A
{
};

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

Result in these errors:

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&)

Shouldn't B inherit A's constructor?

(this is using gcc)

解决方案

In C++03 standard constructors cannot be inherited and you need to inherit them manually one by one by calling base implementation on your own. If your compiler supports C++11 standard, there is a constructor inheritance. For more see Wikipedia C++11 article. With the new standard you write:

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

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

这篇关于继承构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆