2016-03-14 77 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; 
}