首页 > 解决方案 > C++ 返回一个对象的变量

问题描述

我目前正在学习 c++,我遇到了这个问题:错误消息:此代码应为 bool 类型或应转换为 bool。主要功能必须保持不变,所以我想知道,我使用 [A] 行并实际返回一个布尔值。该方法应该比较两个立方体,如果它们相同或不同。

提前致谢!:) <3

#include <iostream>
#include <cfloat>

class cubics
{
private: 
double x,y,z;
bool var;

public: 
cubics same(cubics cube)
{ 
double difference_x = x - cube.x;
double difference_y = y - cube.y;
double difference_z = z - cube.z; 

if  ( // If the difference between two objects are 0, then both cubics are the same; epsilon is used because we calculate with double floating precision to avoid the error) 
                    (difference_x <= std::numeric_limits<double>::epsilon( )) and 
                    (difference_y <= std::numeric_limits<double>::epsilon( )) and 
                    (difference_z <= std::numeric_limits<double>::epsilon( ))
                    )
                {
                    return (cube.var= true);                          // [A] I'm actually returning bool. But does the compiler want me to return the whole object!?
                }
                else
                {
                    return (cube.var=false);                          // [A]
                }
}

int main(){
cubics q2,q3;
cout << "The Cubics q2 and q3 are ";
if (q2.same(q3))                                      // <-- This line confuses me, however it must stay formally for my computerproject the same :) I understand that  it means q2.same(q3) == true, but i don't know how i can return a boolean. I tryed [A]
cout << "same." << endl;
else
cout << "not same." << endl;
}
}

标签: c++

解决方案


要返回一个布尔值,你让函数……返回一个布尔值。

现在,它正试图返回一个类型的对象cubics

cubics same(cubics cube)
^^^^^^

反而:

bool same(cubics cube)
^^^^

return true,或return false,视情况而定。

而已!

bool var根本不需要存在。

我还建议您cube参考;没有必要按价值接受它,这会产生副本。所以:

bool same(const cubics& cube)

推荐阅读