将枚举传递给构造函数

Passing enum to a constructor

本文关键字:构造函数 枚举      更新时间:2023-10-16

我有一个基类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作为参数。

任何帮助都将不胜感激。。。

首先,您应该将Color设置为protected或public。将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);
}

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:枚举对子类不可用,因此它必须至少位于基类Shapeprotected:public:部分中。

string而言。。。请更好地描述你打算做什么。例如,你想打印颜色的名称或它们的数值enum吗?如果是前者,你可以写一个像这样的辅助方法:

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