子类获取超类私有变量c++

Subclass getting superclass private variables c++

本文关键字:变量 c++ 获取 超类 子类      更新时间:2023-10-16

我有一个超类,它有一些私有变量,我需要为一个子类构建一个构造函数。这是超类:

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;
}

我根本无法修改超类。我所能做的就是修改构造函数类以获得超类中私有的值。

派生构造函数不负责设置widthheight。事实上,它甚至看不到它们。您可以使它们成为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变量将相应地反映出来。