4

我有一个基类Shape和一些其他派生类,例如CircleRectangle等等。

这是我的基类

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在构造函数中用作参数。

任何帮助表示赞赏...

4

2 回答 2

9

首先,您应该将颜色设为受保护或公开。将颜色从枚举变为字符串的一种简单方法是使用数组。

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);
}
于 2012-07-24T03:41:11.890 回答
0

an 的类型名enum就是它的名字,在类内部,这个名字被隐式解析为属于这个类。在这种情况下,像这样的构造函数参数Shape(Color color)将定义一个名为的基类构造函数参数color,它具有您的enum Color类型。

然后您的派生类可以调用基构造函数,例如Rectangle(int x, int y, int width, int height, const char* name, Color color): Shape(color) { ... }.

请注意,您还必须更改enum:private:枚举的可见性,子类将无法使用枚举,因此它必须至少位于基类的 aprotected:public:部分中Shape

至于string...请更好地描述你打算做什么。例如,您是否尝试打印颜色的名称或它们的数值enum?如果是前者,您可能会编写一个这样的辅助方法:

void printColor (Color color, std::ostream& os)
{
    switch (color)
    {
    case Red:
        os << "Red";
        break;
    . . . // and so on
    }
}
于 2012-07-24T03:26:43.770 回答