2016-03-14 36 views
0
#include <iostream> 
using namespace std; 

class Distance 
{ 
    private: 
    int feet;    // 0 to infinite 
    int inches;   // 0 to 12 
    public: 
    // required constructors 
    Distance(){ 
    feet = 0; 
    inches = 0; 
    } 
    Distance(int f, int i){ 
    feet = f; 
    inches = i; 
    } 
    // method to display distance 
    void displayDistance() 
    { 
     cout << "F: " << feet << " I:" << inches <<endl; 
    } 
    // overloaded minus (-) operator 
    Distance operator-() 
    { 
    feet = -feet; 
    inches = -inches; 
    return Distance(feet, inches); 
    } 
    }; 
    int main() 
    { 
     Distance D1(11, 10), D2(-5, 11); 

     -D1;      // apply negation 
     D1.displayDistance(); // display D1 

     -D2;      // apply negation 
     D2.displayDistance(); // display D2 

     return 0; 
    } 

如果距離的實例是在操作符 - ()函數返回不應該像新的距離(英尺,英寸)被退回。 這行代碼如何在這裏工作? //返回距離(英尺,英寸);運算符重載:在一元運算符重載函數的返回如何工作在這個代碼?

+1

*不應該像新的距離(英尺,英寸)返回* - C++不是Java或C#。 – PaulMcKenzie

+0

詢問爲您編寫此代碼的人。 – SergeyA

回答

3

如果距離的實例是在操作符 - ()函數返回應該不是退還像new Distance(feet,inches)

沒有,new這裏沒有必要。只需返回一份副本。

實際上否定操作的執行應該像

Distance operator-() const 
{ 
    return Distance(-feet, -inches); 
} 

而不觸及當前實例成員變量(const保證)。

+0

非常感謝! :d針對這個 –

-1

這似乎工作,由於以下原因:

  1. 內部變量英尺和英寸被否定即,可變值。
  2. 然後打印D1或D2的值作爲具體情況而定。
  3. 忽略的對象從運營商,這是錯誤的返回。

一元運算符重載應該是:

Distance & operator-() 
{ 
    feet = -feet; 
    inches = -inches; 
    return *this; 
} 
+0

我的建議 - 沒有一元 - = –

+0

是和否 - =不考慮一元運算符。這裏的目的是顯示如何提供操作符重載。語義,是不正確的否定對象本身內部的值,因此通過@提及的實施πάντα-ῥεῖ然後將正確的方法。但是,如果意圖是使用像腳= -feet;這與簡單地返回感覺不一樣,也與腳不一樣= =? (這裏將使用什麼值?) – Ravi

0

...

// overloaded minus (-) operator 
    Distance &operator-() 
    { 
     feet = -feet; 
     inches = -inches; 
     return (*this); 
    } 
}; 


int main(int argc, const char * argv[]) { 

    Distance D1(11, 10), D2(-5, 11); 

    D1.displayDistance(); 
    -D1; 
    D1.displayDistance(); // apply negation and display D1 

    D2.displayDistance(); 
    (-D2).displayDistance(); // apply negation and display D2 
    (-D2).displayDistance(); // apply negation again and display D2 

    return 0; 
}