gpt4 book ai didi

C++ 使用结构作为某种类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:06:12 26 4
gpt4 key购买 nike

假设我有这个结构:

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

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

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){ ...

它说错误:“operator==”不匹配(操作数类型是“shape”和“std::string”),尽管使用 int 作为类型,它工作正常。

最佳答案

您可以添加operator int:

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

operator int() const { return type; }
};

关于C++ 使用结构作为某种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50457714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com