如何实例化派生类而不必重写代码

How to instantiate derived classes without having to rewrite code?

本文关键字:不必 重写 代码 实例化 派生      更新时间:2023-10-16

假设我有一个:

class A {
    A(int i);
};
class B : A {
};
例如,

不能实例化B(3),因为这个构造函数没有定义。是否有一种方法来实例化一个B对象,它将使用a构造函数,而不必在所有派生类中添加"琐碎"的代码?由于

谢谢

c++ 11有一种方法:

class A {
public:
    A(int i);
};
class B : A {
public:
    using A::A; // use A's constructors
};

如果你正在使用c++ 03,这是我在你的情况下能想到的最好的办法:

class A {
public:
    A(int x) { ... }
};
class B : public A {
public:
    B(int x) : A(x) { ... }
}

你可能也想看看下面的链接,这是一个c#问题,但包含了关于构造函数为什么可以这样做的更详细的答案:

c# -使所有派生类调用基类构造函数

如user491704所说应该是这样的

class mother {
public:
 mother (int a)
 {}
 };
class son : public mother {
public:
 son (int a) : mother (a)
 { }
   };

这是教程的链接