C++读书笔记之 单目运算符重载 取负符号 - 重载

#include <iostream>
using namespace std;

class Distance
{
   private:
      double feet;             // 0 to infinite
      double inches;           // 0 to 12
   public:
      // required constructors
      Distance()
      {
         feet = 0;
         inches = 0;
      }
      Distance(double f, double i)
      {
         feet = f;
         inches = i;
      }
      // method to display distance
      void displayDistance()
      {
         cout << "Feet: " << feet << " Inches:" << inches <<endl;
      }
      // overloaded minus (-) operator
      Distance operator- ()
      {
         feet = -feet;
         inches = -inches;
         return Distance(feet, inches);
      }
};
int main()
{
   Distance D1(-51.2, 42.0), D2(19.91,-20.13);
   cout<<"求负之前:\n";
   D1.displayDistance();    // display D1
   -D1; // apply negation
   cout<<"求负之后:\n";
   D1.displayDistance();    // display D1
   cout<<"求负之前:\n";
   D2.displayDistance();    // display D2
   -D2; // apply negation
   cout<<"求负之后:\n";
   D2.displayDistance();    // display D2

   return 0;
}
/***********************
运行结果:
求负之前:
Feet: -51.2 Inches:42
求负之后:
Feet: 51.2 Inches:-42
求负之前:
Feet: 19.91 Inches:-20.13
求负之后:
Feet: -19.91 Inches:20.13

Process returned 0 (0x0)   execution time : 0.029 s
Press any key to continue.

************************/

你可能感兴趣的:(C++,类,读书笔记,cc++)