2012-07-24 5 views
3

기본 클래스 ShapeCircle, Rectangle 등과 같은 다른 파생 클래스가 있습니다. 열거 형을 생성자에 전달

내 기본 클래스입니다

class Shape { 

private: 
enum Color { 
    Red, 
    Orange, 
    Yellow, 
    Green 
}; 
protected: 
int X; 
int Y; 

// etc... 
}; 

이 내 파생 클래스 중 하나입니다

class Rectangle : public Shape { 
private: 
int Base; 
int Height; 
string shapeName; 

//etc... 
}; 

이 내가 생성자를 호출하는 방법입니다

Rectangle R1(1, 3, 2, 15, "Rectangle 1"); 

내 생성자 :

Rectangle::Rectangle(int x, int y, int B, int H, const string &Name) 
:Shape(x, y) 
{ 
setBase(B); 
setHeight(H); 
setShapeName(Name); 
} 

내 기본 클래스에 enum Color을 사용하여 도형의 색을 전달할 수 있도록 하나의 인수를 생성자에 추가하고 싶습니다. 어떻게해야합니까? 나는 또한 색을 string으로 인쇄하려고합니다. enum을 생성자에서 인수로 사용하는 방법에 대해서는 잘 모릅니다.

어떤 도움에 감사드립니다 ...

+0

나는 열거 색을 비공개로 설정해서는 안된다고 생각합니다. –

+0

현재 생성자는 어떻게 보이나요? 또한'enum Shape :: Color'가'private'이기 때문에 당신이 목표를 달성 할 수 있을지는 의문입니다. – iammilind

+0

@ iammilind 방금 생성자를 추가했습니다. –

답변

8

먼저 Color protected 또는 public으로 설정해야합니다. enum에서 string으로 Color를 만드는 간단한 방법 중 하나는 배열을 사용하는 것입니다.

class Shape { 
public: 
    enum Color { 
     Red = 0, // although it will also be 0 if you don't write this 
     Orange, // this will be 1 
     Yellow, 
     Green 
    }; 

}; 

class Rectangle : public Shape { 
public: 
    Rectangle(int x, int y, int B, int H, Color color); 
}; 

string getColorName(Shape::Color color) { 
    string colorName[] = {"Red", "Orange", "Yellow", "Green"}; 
    return colorName[color]; 
} 

void test() { 
    // now you may call like this: 
    Rectangle r(1,2,3,4, Shape::Red); 
    // get string like this: 
    string colorStr = getColorName(Shape::Yellow); 
} 
+0

'void test()'함수가 나에게 명확하지 않습니다. 답은 당신이'enum'' Shape :: Red'를 넘기는 방식입니다. 포인터 객체를 생성하는 방법을 이해하지 못했습니다.그리고 나는'Shape :: Yellow'뿐만 아니라 어떤 색깔도받을 문자열 stringStr = colorName [Shape :: Yellow];를 원합니다. –

+0

@ Jack in the Box 당신은'string colorStr = colorName [Shape :: Yellow]; '와 같이 모든 색을 표현할 수 있습니다 :'string colorStr = colorName [Shape :: Red];'는'Red'를 줄 것입니다. – Ovilia

+0

모든 색상에 사용할 수있는 일반적인 것을 만들 수 있습니까? –

0

enum의 유형 이름은 그 이름과 이름이 암시 적으로 클래스에 속하는 해결 클래스 내부 입니다. 이 경우 Shape(Color color)과 같은 생성자 인수는 enum Color 형식을 가진 color이라는 기본 클래스 생성자 매개 변수를 정의합니다.

그러면 파생 클래스가 기본 생성자 (예 : Rectangle(int x, int y, int width, int height, const char* name, Color color): Shape(color) { ... }. 그것은 적어도 기본 클래스 Shapeprotected: 또는 public: 섹션에 있어야 있도록 private: 열거 서브 클래스에 사용할 수 없습니다 : 당신은 또한 enum의 가시성을 변경해야합니다

참고.

까지 string ... 의도 한대로 잘 설명해주세요. 예를 들어 색상 이름이나 숫자 enum 값을 인쇄하려고합니까? 이전 버전 인 경우 다음과 같은 도우미 메소드를 작성할 수 있습니다.

void printColor (Color color, std::ostream& os) 
{ 
    switch (color) 
    { 
    case Red: 
     os << "Red"; 
     break; 
    . . . // and so on 
    } 
} 
+0

객체를 생성 할 때 생성자는 어떻게 생겼을까요? Rectangle R1 (1, 3, 2, 15, ???, "Rectangle 1");''??? '에 넣어야 할 사항 –

+1

클래스 외부의 코드에서'enum' 값은 그들이 가지고있는 클래스에 의해 결정됩니다. 예를 들어'Shape :: Red','Shape :: Yellow', ... –