2016-06-14 96 views
-4

我试图使用我的基类“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:错误:之前预期不合格的ID ''令牌 - 46:14:错误:预计在''之前的非限定ID。'代币 - 47:5:错误:'区域'没有指定类型

+1

将这些东西放在构造函数中或其他什么...你知道什么是构造函数吗?你没有使用它们。 – LogicStuff

+0

@LogicStuff你能帮我弄清楚吗? – FL93

+0

这里是关于构造函数的[tutorial](http://www.cplusplus.com/doc/tutorial/classes/)的链接。还有[继承](https:// www。cs.bu.edu/teaching/cpp/inheritance/intro/)。阅读它们; Google是你的朋友。 – NonCreature0714

回答

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

这除了建立一个使用RectangleShapewidthheight,而不是自己的。当在同一地点给出两个名字时,编译器会选择最内层的并隐藏最外层的,这会导致混淆和事故。 Rectangle看到它的widthheight,需要帮助看到Shape中定义的那些。 Shape不知道Rectangle甚至存在,因为Rectangle是在Shape之后定义的。因此Shape只看到其widthheight

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

这需要形状有一个构造函数的宽度和高度

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

+0

这是完美的谢谢! – FL93

+0

不完美。只要有非矩形形状,层次就会下降。回到对象层次结构根目录的每一层应该比以前知道得更少,因为它必须更抽象。形状和矩形一样知道,并且这可以防止形状也代表圆,三角形或其他任何非矩形的东西。形状应该是真的,真的,真的很愚蠢。它不应该知道任何东西。 – user4581301