将枚举传递给构造函数
Passing enum to a constructor
我有一个基类Shape
和一些其他派生类,如Circle
、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
作为参数。
任何帮助都将不胜感激。。。
首先,您应该将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:
枚举对子类不可用,因此它必须至少位于基类Shape
的protected:
或public:
部分中。
就string
而言。。。请更好地描述你打算做什么。例如,你想打印颜色的名称或它们的数值enum
吗?如果是前者,你可以写一个像这样的辅助方法:
void printColor (Color color, std::ostream& os)
{
switch (color)
{
case Red:
os << "Red";
break;
. . . // and so on
}
}
相关文章:
- C++中构造函数中的枚举
- 如何使用默认值为构造函数中的枚举赋值?
- 枚举在构造函数和班级中被调用
- Java 类型的枚举,C++中的自定义值和构造函数
- 包含枚举的结构的C 复制构造函数
- 枚举器而不是用于类实例化的构造函数
- C++:使用结构或枚举重载构造函数之间的区别
- 将成员枚举变量传递给类构造函数时出现无效的重定义错误
- C++枚举复制构造函数和赋值运算符
- 将枚举传递给构造函数
- 构造函数 Qt C++ 中的枚举
- 在构造函数中传递枚举作为参数
- 具有公共重载构造函数的私有枚举
- C++调用带有枚举变量的构造函数
- 构造构造函数采用单个枚举参数的临时对象时出错
- C++ 使用枚举数据类型作为类文件中构造函数的数据类型
- 我可以在类的构造函数中使用枚举吗?
- 枚举作为构造函数c++eclipse的输入
- 具有枚举的结构的C++复制构造函数的签名
- 如何将基类上的枚举传递给子类的构造函数