C++将结构用作某种类型

C++ use struct as some type

本文关键字:种类 类型 结构 C++      更新时间:2023-10-16

>假设我有这个结构:

struct shape{
int type;
shape(){}
shape(int _type){type = _type;}
};

是否可以直接将形状用作整数?在这种情况下,形状将采用其类型的值。例如:

shape s(2);
if     (s == 1) cout<<"this shape is a circle"<<endl;
else if(s == 2) cout<<"this shape is a triangle"<<endl;
else if(s == 3) cout<<"this shape is a rectangle"<<endl;
//...

通常,是否可以使用结构,以便它假定其属性之一的选定值?在 shape 的情况下,它是一个 int,但它可以是字符串或任何其他类型。


编辑:我尝试了@Jarod42使用字符串作为类型建议的代码:

struct shape{
string type;
shape(){}
shape(string _type){type = _type;}
operator string() const {return type;}
}; 

当我写的时候

shape s1("circle");
string s2 = "circle";
if(s1 == s2){ ...

它说错误:与"运算符=="不匹配(操作数类型是"形状"和"std::string">(,尽管使用 int 作为类型,它工作正常。

您可以添加operator int

struct shape{
int type;
shape(){}
shape(int _type) : type(_type) {}
operator int() const { return type; }
};

通常,您可以使用operator T其中T是要强制转换为的类型。如果要强制使用static_cast<T>(my_shape),则可以在前面添加关键字explicit

struct shape
{
int type;
shape() = default;
shape(int _type) : type{ _type } {}
operator int() const { return type; }
explicit operator float() const { return type; }
operator std::string() const
{
switch (type)
{
case 1:
return "circle";
case 2:
return "triangle";
case 3:
return "rectangle";
default:
break;
}
return "(unknown shape)";
}
};

这将适用于内置类型(intfloatdouble(,标准类型(std::stringstd::complex(,自定义结构/类类型,甚至是指针或引用(例如,如果您有静态值数组(。您可能需要考虑是否需要这些转换运算符(封装是完全不同的讨论(,但从概念上讲,这是您的工作方式。

在此示例中,您可能还希望引入用于存储类型值的enum

struct shape
{
enum type_t
{
circle = 1,
triangle,
rectangle
};
type_t type;
operator std::string() const
{
switch (type)
{
case circle:
return "circle";
case triangle:
return "triangle";
case rectangle:
return "rectangle";
default:
break;
}
return "(unknown shape)";
}
shape(type_t _type) : type{ _type } {}
// rest of class as before
};

虽然使用 cast 运算符是一种方法,如 @Jarod42 所示,但我建议使操作更明确一些。

  1. 添加一个函数来获取类型。
  2. if-else语句中使用函数调用和返回值。

struct shape{
int type;
shape(){}
shape(int _type){type = _type;}
int getType() const { return type;}
};

然后

shape s(2);
int type = s.getType();
if     (type == 1) cout<<"this shape is a circle"<<endl;
else if(type == 2) cout<<"this shape is a triangle"<<endl;
else if(type == 3) cout<<"this shape is a rectangle"<<endl;

如果您最终只想按字符串比较形状,那么有一个更简单、更安全的解决方案:

struct shape{
std::string type;
shape() {}
bool operator==(std::string const& rhs) const {
return type == rhs;
}
};
// and if you want to be able to do string == shape.
bool operator==(std::string const& lhs, shape const& rhs) {
return rhs == lhs;
}