2016-06-14 134 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