【问题标题】:Nested Classes and Inheritance [closed]嵌套类和继承
【发布时间】:2016-06-14 17:09:05
【问题描述】:

我正在尝试使用基类“SHAPE”中的函数和派生类“RECTANGLE”在我的类“BIGRECTANGLE”中创建一个更大的矩形。我想在课堂上而不是在主课上进行我的侧面变换,我该怎么办?谢谢!

#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: 错误: '.' 之前的预期 unqualified-id令牌 - 46:14: 错误: '.' 之前的预期 unqualified-id令牌 - 47:5:错误:“区域”没有命名类型

【问题讨论】:

  • 把这些东西放在构造函数或其他什么...你知道构造函数是什么吗?你没有使用它们。
  • @LogicStuff 你能帮我弄清楚吗?
  • 这里是构造函数上的tutorial 的链接。以及inheritance 上的另一个链接。阅读它们; Google 是您的朋友。
  • 另外,你的 main() 函数什么也没做。要么摆脱它,要么用它来展示你的问题。

标签: c++ class inheritance void


【解决方案1】:

凡事都有时间和地点。在

class BIGRectangle: public Rectangle
{
public:

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

初始化类成员的最佳位置是构造函数的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

【讨论】:

  • 非常感谢!
  • 不太完美。一旦你有非矩形的形状,层次结构就会下降。对象层次结构中回到根的每一层都应该比上一层知道的少,因为它必须更抽象。 Shape 与 Rectangle 一样多,这可以防止 Shape 也代表圆形、三角形或其他任何不是矩形的东西。形状应该真的,真的,真的愚蠢。它应该什么都不知道。
猜你喜欢
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 2011-06-19
  • 2017-06-22
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
相关资源
最近更新 更多