是否可以使用基类构造函数通过派生类将值初始化为基类私有成员?
Is it possible to use the base class constructor to initialize values to base class private members using derived class?
我想做的是使用Rectangle
类设置Shape
类的width
和height
变量。
形状.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
对象来初始化私有类Shape
的width
和height
变量。有什么办法可以做到这一点吗?还是需要将width
和height
变量设置为受保护?
您当前的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;
}
相关文章:
- C++类 - 初始化列表 - 递归 - 按值传递
- 何时为派生类初始化 vptr?
- 虚拟基类初始化
- 类初始化中的静态 lambda
- 如何防止在基类初始化器中调用默认构造函数?
- 如何在派生类中存储基类初始化期间获得的信息
- 是否可以在基类初始化器列表中传递成员对象
- 多重继承、复制构造函数和基类初始化
- 是否将类初始化的常量成员传递给基构造函数
- C++是否要求您从其派生类初始化基类成员
- 如何使用运行时选择基 CTOR 初始化不可复制的基类
- 继承和复制构造函数-如何从基类初始化私有字段
- 在使用虚拟继承时,我可以避免重复的基类初始化吗
- 基类初始化器和成员变量初始化器的顺序重要吗
- 在初始化列表中基类初始化之前调用函数
- 虚拟基类初始化
- 尽管类名与C++完全匹配,但模板基类初始化构造函数失败
- 初始化派生类初始化器列表中的基类成员
- 了解基类初始化
- 关于派生类初始化中的基类