C++使用struct作为某种类型

Dan*_*iel 4 c++ struct

假设我有这个结构:

struct shape{
    int type;
    shape(){}
    shape(int _type){type = _type;}
};
Run Code Online (Sandbox Code Playgroud)

可以直接使用shape 作为int吗?在这种情况下,形状将采用其类型的值.例如:

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;
//...
Run Code Online (Sandbox Code Playgroud)

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


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

struct shape{
    string type;
    shape(){}
    shape(string _type){type = _type;}
    operator string() const {return type;}
}; 
Run Code Online (Sandbox Code Playgroud)

当我写作

shape s1("circle");
string s2 = "circle";
if(s1 == s2){ ...
Run Code Online (Sandbox Code Playgroud)

它说错误:'operator =='没有匹配(操作数类型是'shape'和'std :: string),虽然int是类型,但它工作正常.

Jar*_*d42 5

您可以添加operator int:

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

    operator int() const { return type; }
};
Run Code Online (Sandbox Code Playgroud)