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

+1

환영은 그림으로 코드를 게시하지 않습니다. 도움을 받기가 매우 어렵습니다. – Linuxios

답변

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(); 
} 
나는 당신의 클래스 이름에서 이해할 수있는 내용에 따라, 당신은 오히려 그들 사이의 IS-A 관계를 모델링하기 위해 상속을 사용한다

또는 interface with virtual function을 사용하십시오.

+0

도움 주셔서 감사합니다. – user1681664

1

사람들은 서브 클래스 (즉, 파생 클래스), 오히려 중첩 클래스 (질문의 제목이 말하는 것처럼)하지 않습니다.

중첩 된 클래스에서 변수를 볼 수있게 설정하는 방법을 알려 드리고 싶습니다. 질문에 답할 것 같지 않습니다.

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

main에서 길이와 너비를 어떻게 설정합니까? – user1681664

+0

@ user1681664 : 추가했습니다. –