c++ - 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;
}
}
解决方案
要返回一个布尔值,你让函数……返回一个布尔值。
现在,它正试图返回一个类型的对象cubics
:
cubics same(cubics cube)
^^^^^^
反而:
bool same(cubics cube)
^^^^
和return true
,或return false
,视情况而定。
而已!
你bool var
根本不需要存在。
我还建议您cube
参考;没有必要按价值接受它,这会产生副本。所以:
bool same(const cubics& cube)
推荐阅读
- authentication - 如何使用cyberark密码验证ansible托管节点
- c# - 无法将 .NET 应用程序部署到应用程序引擎 - kaniko-projec 执行器错误
- sql - 从第二个表左加入计数(*)
- scala - MVar 公平性保证?
- java - 这个类命令在 kotlin 中意味着什么?
- android - 而不是意外的紫色,如何为按钮使用白色默认颜色?
- javascript - ReactJS TypeError:无法设置属性“onclick”为空
- javascript - 点击超过2张图片时如何使图片发生变化?
- java - 点击图片会导致安卓应用崩溃
- android - 在 Android LayoutInflater 中编辑 TextView