【发布时间】:2018-05-21 23:15:35
【问题描述】:
假设我有这个结构:
struct shape{
int type;
shape(){}
shape(int _type){type = _type;}
};
是否可以直接将形状用作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){ ...
它说 error: no match for 'operator=='(操作数类型是 'shape' 和 'std::string),尽管使用 int 作为类型,它工作正常。
【问题讨论】:
-
仅供参考,如果相当危险且通常不明智,则沿着这条路走下去。你经常隐含地购买你的类不是为这些 API 设计的。这只有在你有明确的 is-a 关系时才有意义(你的 shape 类绝对没有
int。s+3是什么意思?这很重要,因为它不再导致编译错误。)跨度> -
cout << "this shape is a " << (s == 1 ? "circle" : s == 2 ? "triangle" : s == 3 ? "rectangle" : "(unknown shape)") << "\n";或者只使用switch语句。 ;) -
@Frank 这就是为什么您可以进行转换
explicit,但当然,对于更高度开发的shapeAPI 来说,拥有流运算符、比较运算符等也可能更有意义让类的最终用户以相关方式访问形状,而不会暴露实现细节。当然你已经知道了。 -
int 是原始数据类型,但字符串不是。您需要重载 == 运算符才能在 if 条件下进行比较。