在使用模板时,我遇到需要使基类构造函数可从继承类访问以创建对象,以减少复制/粘贴操作。
我想通过这样做using
关键字与函数 case 的方式相同,但不起作用。
class A
{
public:
A(int val) {}
};
class B : public A
{
};
class C : public A
{
public:
C(const string &val) {}
};
class D : public A
{
public:
D(const string &val) {}
using A::A; // g++ error: A::A names constructor
};
void main()
{
B b(10); // Ok. (A::A constructor is not overlapped)
C c(10); // error: no matching function to call to 'C::C(int)'
}
所以我的问题:在声明继承类中的新构造函数之后,有什么方法可以导入基类构造函数吗?
或者只有一种选择来声明新的构造函数并从初始值设定项列表中调用基本构造函数?
是的,从 C++11 开始:
struct B2 {
B2(int = 13, int = 42);
};
struct D2 : B2 {
using B2::B2;
// The set of inherited constructors is
// 1. B2(const B2&)
// 2. B2(B2&&)
// 3. B2(int = 13, int = 42)
// 4. B2(int = 13)
// 5. B2()
// D2 has the following constructors:
// 1. D2()
// 2. D2(const D2&)
// 3. D2(D2&&)
// 4. D2(int, int) <- inherited
// 5. D2(int) <- inherited
};
有关更多信息,请参阅http://en.cppreference.com/w/cpp/language/using_declaration http://en.cppreference.com/w/cpp/language/using_declaration
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)