我正在尝试编写一个返回 1 和 0 而不是 true 或 false 的代码。但这似乎不对。
int Short_Vector::operator==(const Short_Vector& obj){
if(a == obj.a && b == obj.b && c == obj.c && d == obj.d){
return 1;
}else{
return 0;
}
}
所以它应该为每个变量返回一个值。
我也试过这个:
int Short_Vector::operator==(const Short_Vector& obj){
int a_tf, b_tf, c_tf, d_tf;
if(a == obj.a){
a_tf = 1;
}else{
a_tf = 0;
}
if(b == obj.b){
b_tf = 1;
}else{
b_tf = 0;
}
if(c == obj.c){
c_tf = 1;
}else{
c_tf = 0;
}
if(d == obj.d){
d_tf = 1;
}else{
d_tf = 0;
}
return(a_tf, b_tf, c_tf, d_tf)
}
但是我得到关于逗号是运算符的错误。
编辑
获取错误:错误:从“int”到非标量类型“Short_Vector”的转换。
我试图表示一个看起来像 [9,1,5,5] 的 vector 。
那我说
`Short_Vector a(2, 6, 9, 4);
Short_Vector b(3, 8, 7, 6);
Short_Vector c = a == b;
cout<<c;`
然后输出为:[0,0,0,0]
最佳答案
第二种方法无效,因为返回类型是“int”,而“(a_tf, b_tf, c_tf, d_tf)”不是 int,而是 4 个以逗号分隔的 int。
因为你想返回 4 个 bool 值,你可以执行以下操作:
int Short_Vector::operator==(const Short_Vector& obj)
{
//...
return (a_tf) | (b_tf << 1) | (c_tf << 2) | (d_tf << 3);
}
//the caller would do the follwoing:
int result = (MyObject1 == MyObject2);
if(result & (1 << 1) //b_tf is set to 1;
{
}
if(result & (1 << 3) //d_tf is set to 1;
{
}
关于c++ - 运算符重载(int as bool),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16469455/