📄 hour14_2.cpp
字号:
// 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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -