[英]C++ Return a Variable of an object
我目前正在學習 c++,我遇到了這個問題:錯誤消息:此代碼應為 bool 類型或應轉換為 bool。 主要的 function 必須保持不變,所以我想知道我使用 [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;
}
}
要返回 boolean,請執行函數……返回 boolean。
現在,它正在嘗試返回一個cubics
類型的立方體:
cubics same(cubics cube)
^^^^^^
反而:
bool same(cubics cube)
^^^^
並酌情return true
或return false
。
而已!
您的bool var
根本不需要存在。
我還建議您參考cube
; 沒有必要按價值接受它,這會產生副本。 所以:
bool same(const cubics& cube)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.