C++ operator操作符重载(++,--,-,+,())
生活随笔
收集整理的這篇文章主要介紹了
C++ operator操作符重载(++,--,-,+,())
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++中++,--操作符重載需要說明是++(--)在操作數前面,還是在操作數后面,區別如下:
代碼經過測試無誤(起碼我這里沒問題^_^)
Code?1#include?<iostream>
?2#include?<cstdlib>
?3using?namespace?std;
?4template<typename?T>?class?A
?5{
?6public:
?7????A():?m_(0){
?8????}
?9????//?+
10????const?T?operator?+?(const?T&?rhs)
11????{
12???????????//?need?to?be?repaired?,?but?see?it?is?only?a?demo
13???????????return?(this->m_?+?rhs);
14????}
15????//?-
16????const?T?operator?-?(const?T&?rhs){
17???????????//?need?to?be?repaired?,?but?see?it?is?only?a?demo
18?????????????return?(this->m_?-?rhs);
19????}
20????T?getM(){
21??????return?m_;
22????}
23????
24????//?++在前的模式,這里返回的是引用?,準許++++A
25????A&?operator?++?(){
26???????????(this->m_)++;
27???????????return?*this;
28????}
29????//?++?在后,這里返回的是一個新的A類型變量,且不可改變
30????//?目的是防止出現?A++++情況
31????const?A?operator?++(int?a){
32???????????A<T>?b?=?*this;
33???????????(this->m_)++;
34???????????return?b;
35????}
36private:
37????T?m_;
38};
39
40
41int?main(void){
42????int?i?=?0;
43????cout<<++++i<<endl;
44????//?i++++?is?not?allowed
45????A<int>?a;
46????A<int>?b?=?++a;
47????cout<<b.getM()<<endl;
48????A<int>?c?=?a++;
49????cout<<c.getM()<<endl;
50????cout<<a.getM()<<endl;
51????int?t?=?a+2;
52????cout<<t<<endl;
53????system("pause");
54????return?0;????
55????
56}?
?
轉載于:https://www.cnblogs.com/diyunpeng/archive/2009/10/21/1587554.html
總結
以上是生活随笔為你收集整理的C++ operator操作符重载(++,--,-,+,())的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UML 面向对象分析与设计
- 下一篇: dhl:mvc用户登陆身份验证