是否可以使用基类构造函数通过派生类将值初始化为基类私有成员?

Is it possible to use the base class constructor to initialize values to base class private members using derived class?

本文关键字:基类 初始化 成员 可以使 构造函数 派生 是否      更新时间:2023-10-16

我想做的是使用Rectangle类设置Shape类的widthheight变量。

形状.h

class Shape
{
public:
Shape(int x, int y);
private:
int width;
int height;
};

形状.cpp

Shape::Shape(int x, int y): width(x), height(y)
{
}

矩形.h

class Rectangle: public Shape
{
public:
Rectangle(int, int);
};

矩形.cpp

Rectangle::Rectangle(int x, int y):Shape(x, y)
{
}

主.cpp

int main()
{
Rectangle rec(10,7);
return 0;
}

我想做的是使用rec对象来初始化私有类Shapewidthheight变量。有什么办法可以做到这一点吗?还是需要将widthheight变量设置为受保护?

您当前的Rectangle实现使用其参数正确调用基构造函数。使用现代C++(至少 C++11),可以使用继承构造函数简化Rectangle的实现:

struct Rectangle : public Shape {
using Shape::Shape;
};

要访问private成员,需要将其更改为public,或者您需要在基类中实现 getter 方法。 或者,您可以使private成员protected并在派生类中实现 getter(尽管height是所有派生类通用的,因此将 getter 放在基类中是合适的)。

class Shape {
/* ... */
public:
int get_height() const { return height; }
};
std::cout << rec.get_height() << std::endl;

您的代码已经编译得很好,除了您无法访问主函数中的rec.height,因为它是私有的。

以公共方式继承的派生类可以访问基于类的公共构造函数。

int main()
{
Rectangle rec(10,7);
// cout << rec.height << endl;  <----------- disabled
return 0;
}