2013-02-24 123 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