如何实例化派生类而不必重写代码
How to instantiate derived classes without having to rewrite code?
假设我有一个:
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)
{ }
};
这是教程的链接
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- 在 C++ 中用派生类型重写成员函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 方法重写线程C++中的概念
- 为重写std::exception的库生成swig接口时出错
- 如何强制从重写方法调用重写的方法基方法?
- 用于C++的静态二进制检测或二进制重写工具和框架
- 如何将 if else 语句重写为 switch 语句
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 用 C 重写C++类
- 是否总是可以将使用递归编写的程序重写为不使用递归的程序C++,性能观点是什么?
- 重写虚拟函数和继承
- C++调用使用重写函数的父类函数
- 重写打印函数而不是覆盖基类
- 不允许在类定义之外重写
- 如何公开库的枚举,以便我的代码不必键入整个命名空间来使用该枚举?
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- C++:从抽象类重写纯虚拟运算符重载
- 如何实例化派生类而不必重写代码