嵌套 类 和继承

Nested Classes and Inheritance

我正在尝试使用我的基础 class "SHAPE" 中的函数和派生的 class "RECTANGLE" 在我的 class "BIGRECTANGLE"。我想在 class 内而不是在主体内进行两侧变换,我该怎么办?谢谢!

#include <iostream>

using namespace std;

// Base class Shape
class Shape
{
public:

    void ResizeW(int w)
    {
        width = w;
    }
    void ResizeH(int h)
    {
        height = h;
    }
protected:

    int width;
    int height;
};

// Primitive Shape

class Rectangle: public Shape
{
public:

    int width = 2;
    int height = 1;
    int getArea()
    {
        return (width * height);
    }
};

// Derived class

class BIGRectangle: public Rectangle
{
public:

    int area;
    Rectangle.ResizeW(8);
    Rectangle.ResizeH(4);
    area = Rectangle.getArea();
};

int main(void)
{
    return 0;
}

这些是我遇到的错误: - 45:14:错误:'.' 之前应为非限定 ID令牌 - 46:14:错误:'.' 之前应为非限定 ID令牌 - 47:5: 错误: 'area' 没有命名类型

凡事都有时间和地点。在

class BIGRectangle: public Rectangle
{
public:

    int area;
    Rectangle.ResizeW(8);
    Rectangle.ResizeH(4);
    area = Rectangle.getArea();
};

初始化class成员的最佳位置是构造函数的Member Initializer List。例如:

class BIGRectangle: public Rectangle
{
public:

    int area;

    BIGRectangle():Rectangle(8, 4), area(getArea())
    {
    }
};

这就是说,为我构建一个 BIGRectangle,它由一个 8 x 4 的 Rectangle 组成,并存储 Rectangle 的计算 area

但这需要 Rectangle 有一个需要高度和宽度的构造函数。

class Rectangle: public Shape
{
public:

    // no need for these because they hide the width and height of Shape
    // int width = 2;
    // int height = 1;
    Rectangle(int width, int height): Shape(width, height)
    {

    }
    int getArea()
    {
        return (width * height);
    }
};

该添加构建了一个 Rectangle,它使用 Shapewidthheight 而不是它自己的。当在同一个地方给出两个名字时,编译器会选择声明在最里面的那个而隐藏最外面的,这会导致混乱和事故。 Rectangle 看到它的 widthheight,需要帮助才能看到 Shape 中定义的那些。 Shape 甚至不知道 Rectangle 存在,因为 Rectangle 是在 Shape 之后定义的。结果 Shape 只能看到它的 widthheight.

当您调用 getArea 时,这会导致一些真正令人讨厌的 juju。当前版本设置 Shapewidthheight 并使用 Rectanglewidthheight 来计算面积。不是你想要的。

这就要求 Shape 有一个接受宽度和高度的构造函数

class Shape
{
public:
    Shape(int inwidth,
          int inheight): width(inwidth), height(inheight)
    {

    }
    void ResizeW(int w)
    {
        width = w;
    }
    void ResizeH(int h)
    {
        height = h;
    }
protected:

    int width;
    int height;
};

请注意参数是 inwidth,而不是 width。这不是绝对必要的,但出于与上述相同的原因,在同一地点或附近两次使用相同的名称是不好的形式:同一时间在同一地点使用相同的名称是不好的。

但这会问一个问题,当你有 Circle 时会发生什么,这是一个 Shape。圆圈没有宽度或高度,因此您可能需要重新考虑 Shape.