hour14_2.cpp

来自「《24学时精通c++》的随书源码的下半部分。欢迎下载学习。」· C++ 代码 · 共 53 行

CPP
53
字号
// Listing 14.3 
// Returning the dereferenced this pointer 
#include <iostream>  

class Counter 
{
public:
     Counter();
     ~Counter(){}
     int GetItsVal()const { return itsVal; }
     void SetItsVal(int x) {itsVal = x; }
     const Counter& operator++ ();      // prefix
     const Counter operator++ (int); // postfix
private:
     int itsVal; 
};

Counter::Counter():
itsVal(0) 
{}

const Counter& Counter::operator++()   // prefix 
{
     --itsVal;       // note that the action doesn't match the name (it decrements!)
     return *this; 
}

const Counter Counter::operator++(int)   // postfix 
{
     Counter temp(*this);
     --itsVal;       // note that the action doesn't match the name (it decrements!)
     return temp; 
}

int main() 
{
     Counter i;
     std::cout << "The value of i is " << i.GetItsVal()
          << std::endl;
     i++;
     std::cout << "The value of i is " << i.GetItsVal()
          << std::endl;
     ++i;
     std::cout << "The value of i is " << i.GetItsVal()
          << std::endl;
     Counter a = ++i;
     std::cout << "The value of a: " << a.GetItsVal();
     std::cout << " and i: " << i.GetItsVal() << std::endl;
     a = i++;
     std::cout << "The value of a: " << a.GetItsVal();
     std::cout << " and i: " << i.GetItsVal() << std::endl;
     return 0; 
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?