子类获取超类私有变量c++
Subclass getting superclass private variables c++
我有一个超类,它有一些私有变量,我需要为一个子类构建一个构造函数。这是超类:
class Shape {
public:
Shape(double w, double h);
string toString();
private:
double width;
double height;
};
超类构造函数:
Shape::Shape(double w, double h) {
width = w;
height = h;
}
子类:
class Rectangle : public Shape {
public:
Rectangle(double w, double h, int s);
string toString();
private:
int sides;
};
我的子类构造函数如下:
Rectangle::Rectangle(double w, double h, int s) : Shape(w, h) {
width = w;
height = h;
sides = s;
}
我根本无法修改超类。我所能做的就是修改构造函数类以获得超类中私有的值。
派生构造函数不负责设置width
和height
。事实上,它甚至看不到它们。您可以使它们成为protected
甚至public
,但为什么?这是一件好事,只有基地可以管理自己的成员。
您已经在为基构造函数指定参数了,所以可以开始了。一旦你去掉多余的和断线,这里就没有问题了:
struct Shape
{
Shape(double w, double h)
{
width = w;
height = h;
}
private:
double width;
double height;
};
struct Rectangle : Shape
{
Rectangle(double w, double h, int s)
: Shape(w, h)
{
sides = s;
}
private:
int sides;
};
顺便说一句,在可能的情况下,您应该标准化使用ctor初始化程序,而不是只在某些时候使用它,然后在其他时候从主体分配:
struct Shape
{
Shape(double w, double h)
: width(w)
, height(h)
{}
private:
double width;
double height;
};
struct Rectangle : Shape
{
Rectangle(double w, double h, int s)
: Shape(w, h)
, sides(s)
{}
private:
int sides;
};
如果我理解得对,你想在通过子类构造超类的私有变量之后修改它们。
首先,在超类中实现set()
方法,以便我们可以访问其private
变量:
Shape.h
class Shape {
public:
Shape(double w, double h);
string toString();
//here
setWidth(double);
setHeight(double);
private:
double width;
double height;
};
形状.cpp
Shape::setWidth(double w) { width = w; }
Shape::setHeight(double h) { height = h; }
然后,您可以通过子类调用超类set()
方法
矩形构造函数:
Rectangle(double w, double h, int s)
: width(w) // subclass width
, height(h)
{
// modify subclass width & height as desired here
//then reflect superclass width & height according to subclass
Shape::setWidth(width);
Shape::setHeight(height);
}
Shape::setWidth()
和Shape::setHeight()
可以在子类和超类中的任何地方调用,private
变量将相应地反映出来。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 变量没有改变?通过向量的函数调用