2013-02-24 118 views
0

我想從這個去: enter image description here嵌套類變量調用

要這樣: enter image description here

我會怎麼做呢?知道子類square和rectangle的函數如何使用父類形狀的變量?

我將如何設置長度和寬度從主?

#include <iostream> 
#include <cmath> 
using namespace std; 

class SHAPES 
{ 
     public: 
     class SQUARE 
     { 
      int perimeter(int length, int width) 
      { 
       return 4*length; 
      } 
      int area(int length, int width) 
      { 
       return length*length; 
      } 
     }; 
     public: 
     class RECTANGLE 
     { 
      int perimeter(int length, int width) 
      { 
       return 2*length + 2*width; 
      } 
      int area(int length, int width) 
      { 
      return length*width; 
      } 
     }; 

}; 
+0

在這裏複製並粘貼你的代碼;不要只是拍屏幕截圖。請隨時閱讀本網站上的其他一些問題,以瞭解預期的內容。 – chrisaycock 2013-02-24 16:17:57

+1

請勿將代碼張貼爲圖片。這使得很難提供幫助。 – Linuxios 2013-02-24 16:21:05

回答

1

我建議其他(更好?):

class Shape 
{ 
protected: 
    int length,width; 
public: 
    Shape(int l, int w): length(l), width(w){} 
    int primeter() const 
    { 
     return (length + width) * 2; 
    } 
    int area() const 
    { 
     return length * width; 
    } 
}; 

class Rectangle : public Shape 
{ 
public 
    Rectangle(int l, int w) : Shape(l,w){} 
}; 

class Square : public Shape 
{ 
public: 
    Square(int l): Shape(l,l){} 
}; 


int main() 
{ 
    Rectangle r(5,4); 
    Square s(6); 

    r.area(); 
    s.area(); 
} 

或使用interface with virtual function

+0

謝謝你的幫助。 – user1681664 2013-02-24 16:38:22

1

這些都不是子類(即派生類),而是嵌套類(如你的問題的標題所說)。

我不認爲我會回答你的真實問題,如果我要告訴你如何讓這些變量在嵌套類中可見。根據我可以從你的類的名字明白了,你倒是應該使用繼承來的IS-A它們之間的關係進行建模:格式

class SHAPE 
{ 
public: // <-- To make the class constructor visible 
    SHAPE(int l, int w) : length(l), width(w) { } // <-- Class constructor 
    ... 
protected: // <-- To make sure these variables are visible to subclasses 
    int length; 
    int width; 
}; 

class SQUARE : public SHAPE // <-- To declare public inheritance 
{ 
public: 
    SQUARE(int l) : SHAPE(l, l) { } // <-- Forward arguments to base constructor 
    int perimeter() const // <-- I would also add the const qualifier 
    { 
     return 4 * length; 
    } 
    ... 
}; 

class RECTANGLE : public SHAPE 
{ 
    // Similarly here... 
}; 

int main() 
{ 
    SQUARE s(5); 
    cout << s.perimeter(); 
} 
+0

我將如何設置長度和寬度從主? – user1681664 2013-02-24 16:27:10

+0

@ user1681664:補充說明。 – 2013-02-24 16:28:07