您的位置:首页 > 其它

信管14:运算符重载示例四

2015-05-27 20:42 288 查看
/*运算符作为类成员  */

#include <iostream>

using namespace std;

class Increase

{

public:
Increase(int x):value(x){}
Increase & operator++();      // 前自增
Increase operator++(int);     // 后自增
void display()
{ cout <<"the value is " <<value <<endl; }

private:
int value;

};

Increase & Increase::operator++()

{ value++;                      // 先进行自增运算
return *this;                 // 再返回原对象

}

Increase Increase::operator++(int)

{ Increase temp(*this);         // 临时对象存放原有对象值
value++;                      // 原有对象自增修改
return temp;                  // 返回原有对象值

}

int main()

{ Increase n(20);
n.display();                  //20
(n++).display();              // 显示20
n.display();                  // 显示原有对象21
(++n).display();              //22
n.display();                  //22
++(++n);

n.display();                 //24
(n++)++;
// 第二次自增操作对临时对象进行
n.display();

        system("pause");
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: