Jac*_*Box 4 c++ enums constructor
我有一个基类Shape和一些其他派生类Circle,Rectangle等等.
这是我的基类
class Shape {
private:
enum Color {
Red,
Orange,
Yellow,
Green
};
protected:
int X;
int Y;
// etc...
};
Run Code Online (Sandbox Code Playgroud)
这是我的派生类之一
class Rectangle : public Shape {
private:
int Base;
int Height;
string shapeName;
//etc...
};
Run Code Online (Sandbox Code Playgroud)
这就是我调用构造函数的方式:
Rectangle R1(1, 3, 2, 15, "Rectangle 1");
Run Code Online (Sandbox Code Playgroud)
我的构造函数:
Rectangle::Rectangle(int x, int y, int B, int H, const string &Name)
:Shape(x, y)
{
setBase(B);
setHeight(H);
setShapeName(Name);
}
Run Code Online (Sandbox Code Playgroud)
我想在构造函数中添加一个参数,这样我就可以enum Color在我的基类中传递形状的颜色.我怎样才能做到这一点?我也想把颜色打印成一个string.我不知道如何enum在构造函数中用作参数.
任何帮助表示赞赏......
首先,您应该使Color受到保护或公开.从枚举到字符串制作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);
}
Run Code Online (Sandbox Code Playgroud)