C++ 編程語言可以被看做是C語言的升級(jí)版本,它能夠支持C語言中的所有功能,而且在其他方面也有很大的提升。其中,在C++操作符重載中++,--需要說明是++(--)在操作數(shù)前面,還是在操作數(shù)后面,區(qū)別如下:
C++操作符重載代碼經(jīng)過測試無誤(起碼我這里沒問題^_^)
1.#include < iostream>
2.#include < cstdlib>
3.using namespace std;
www.601456.com 4.template< typename T> class A
5.{
6.public:
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);
www.liuhebao.com 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);
www.yzjxsp.com 19.}
20.T getM(){
21.return m_;
22.}
23.// ++在前的模式,這里返回的是引用 ,準(zhǔn)許++++A
24.A& operator ++ {
www.yzyedu.com 25.(this->m_)++;
26.return *this;
27.}
28.// ++ 在后,這里返回的是一個(gè)新的A類型變量,且不可改變
29.// 目的是防止出現(xiàn) A++++情況
30.const A operator ++(int a){
31.A< T> b = *this;
32.(this->m_)++;
33.return b;
34.}
35.private:
36.T m_;
37.};
38.int main(void){
39.int i = 0;
www.yzjjx.com 40.cout< < ++++i< < endl;
41.// i++++ is not allowed
42.A< int> a;
43.A< int> b = ++a;
44.cout< < b.getM()< < endl;
45.A< int> c = a++;
46.cout< < c.getM()< < endl;
47.cout< < a.getM()< < endl;
48.int t = a+2;
www.yzsws.com 49.cout< < t< < endl;
50.system("pause");
51.return 0;
52.}
www.szfuao.com 以上就是對(duì)C++操作符重載的相關(guān)介紹。