2014-09-27 41 views
0

我知道這意味着什麼,但在我的情況下,我不明白爲什麼我的IDE爲此大喊大叫。表達式必須是我們班的一個可修改的左值

Rational operator*(const Rational& that1, const Rational& that2) 
{ 
    Rational temp(that1); 
    temp.getNom() *= that2.getNom(); 
    temp.getDenom() *= that2.getDenom(); 
    return temp; 
} 

int Rational::getNom() const 
{ 
    return m_iNom/gcd(m_iNom, m_iDenom); 
} 
int Rational::getDenom() const 
{ 
    return m_iDenom/gcd(m_iNom, m_iDenom); 
} 

float Rational::gcd(int a, int b) 
{ 
    if (b == 0) 
     return a; 
    return gcd(b, a % b); 
} 

m_iNom & m_iDenom是理性的類中私有數據成員。

我得到「表達必須修改的左值」在:

temp.getNom() *= that2.getNom(); 
temp.getDenom() *= that2.getDenom(); 

回答

1

不能影響值的函數或方法的返回。

temp.getNom() *= that2.getNom();就像temp.getNom() = temp.getNom() * that2.getNom();

這就像寫2 = 2 * 3並設置2 = 5 ...沒有任何意義!

+0

如果我想返回該怎麼辦nom和denom並通過函數調用來改變它,就像我在這裏做的那樣,那麼我是否需要做setter? – 2014-09-27 12:01:12

+0

如果你被允許,調用setter('.setNom'?)或直接訪問該字段。 – 2014-09-27 12:02:59

+0

希望我可以做到這一點,沒有setters,但好的感謝解釋 – 2014-09-27 12:05:21

1

正如編譯器所說的,你不能指定返回值。
即使您可以分配給返回值,成員變量也不會受到影響 - 訪問器返回成員變量的值,而不是實際變量。

這樣做的慣用方法是先實現operator *=爲成員:

Rational& operator *= (const Rational& that) 
{ 
    m_iNom *= that.m_iNom; 
    m_iDenom *= that.m_iDenom; 
    return *this; 
} 

,然後用它來實現*

Rational operator*(const Rational& that1, const Rational& that2) 
{ 
    Rational result(that1); 
    result *= that2; 
    return result; 
} 
相關問題