嵌套类和继承

时间:2016-06-14 17:09:06

标签: c++ class inheritance void

我试图使用我基类中的函数" 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:错误:在#39;之前预期不合格的身份。&#39;代币 - 46:14:错误:在#39;之前预期不合格的身份。&#39;代币 - 47:5:错误:&#39; area&#39;没有命名类型

1 个答案:

答案 0 :(得分: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构成的Rectangle,它是8乘4并存储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的{​​{1}}和Shape而不是自己的width的{​​{1}}。当在同一个地方给出两个名字时,编译器会选择一个声明最内层的名称并隐藏最外层名称,这会导致混乱和意外。 height看到了Rectanglewidth,需要帮助才能看到height中定义的内容。 Shape无法确定Shape是否存在,因为在Rectangle之后定义了Rectangle。因此,Shape只会看到Shapewidth

当你致电height时,这会导致一些真正讨厌的juju。当前版本设置getArea的{​​{1}}和Shape,并使用width的{​​{1}}和height来计算区域。不是你想要发生的事情。

这需要Shape有一个带宽度和高度的构造函数

Rectangle

请注意参数是width,而不是height。这不是绝对必要的,但是由于与上述相同的原因,在相同的地方或近距离使用相同的名称两次是不好的形式:同一地点的同一个名字同时是坏的。

但是,这会询问当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