【发布时间】:2021-11-11 13:38:22
【问题描述】:
假设我想利用基类构造函数来创建派生类对象。
这是我的做法:
class base
{
int x, y, z;
public:
base(int x, int y, int z)
:
x(x),
y(y),
z(z)
{
std::cout << "base class constructor called\n";
}
int get_x() const { return x; }
int get_y() const { return y; }
int get_z() const { return z; }
};
class derived : public base
{
int value;
public:
derived(int x, int y, int z, int value)
:
base(x, y, z),
value(value)
{
std::cout << "derived class constructor called\n";
};
int get_val() const { return value; } ;
};
我的问题:这是解决该问题的正确方法吗?或者,在派生类构造函数中如何使用基类构造函数有更好的方法吗?
【问题讨论】:
-
显示的代码看起来不错。
-
derived(base b, int value)这样的构造函数可能有意义。 -
是的,这是创建派生对象的标准方法。
标签: c++ c++11 inheritance c++14