C++有個關鍵字operator,具體怎麼用呢?到底什麼是操作符重載,上代碼分析。
#include <cstdlib>
#include <iostream>
using namespace std;
class Operator
{
private:
int a;
int b;
public:
Operator(int a, int b)
{
this->a = a;
this->b = b;
}
~Operator()
{
}
Operator operator+ (const Operator& obj);
Operator operator++ (int);
Operator& operator++ ();
bool operator== (const Operator& obj);
bool operator!= (const Operator& obj);
friend ostream& operator<< (ostream& out, const Operator& obj);
};
ostream& operator<< (ostream& out, const Operator& obj)
{
out << obj.a << "+" << obj.b << "i";
return out;
}
Operator Operator::operator+ (const Operator& obj)
{
Operator op(0,0);
op.a = a + obj.a;
op.b = b + obj.b;
return op;
}
Operator Operator::operator++ (int)
{
Operator ret = *this;
a++;
b++;
return ret;
}
Operator& Operator::operator++ ()
{
++a;
++b;
return *this;
}
bool Operator::operator== (const Operator& obj)
{
return (a == obj.a) && (b = obj.b);
}
bool Operator::operator!= (const Operator& obj)
{
return !(*this == obj);
}
int main(int argc, char *argv[])
{
Operator a1(1,2);
Operator a2(3,4);
Operator a3(0,0);
//a3 = a1 + a2;
a1++;
++a2;
a3 = a1;
if (a1 != a2)
{
cout << "a1 != a2" << endl;
}
if (a1 == a3)
{
cout << "a1 == a3" << endl;
}
cout << a1 << endl;
cout << a2 << endl;
cout << a3 << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
在C++中它的假髮只能針對兩個數字,而我們想要兩個對象相加時,就要重載操作符+,那麼重載操作符的時候,我們是用友員函數還是成員函數,這裏根據實際需要,有兩點要求:
(1)當無法修改左操作數的時候,只能使用全局函數重載
(2)=、[]、()、->四個操作符只能通過成員函數重載
上述的"<<"左操作數out是ostream類,我們無法修改,所以只能用友員函數重載,而++、+等操作符我們可以直接用成員函數重載。
這裏的++操作包括前++和後++,所有在重載的時候,我們用一個int作爲佔位參數來區別。
注意:不要去重載&&和||操作符,爲什麼呢?看下面的例子。
#include <cstdlib>
#include <iostream>
using namespace std;
class Test
{
private:
int i;
public:
Test(int i)
{
this->i = i;
}
Test operator+ (const Test& obj)
{
Test ret(0);
ret.i = i + obj.i;
cout << "Test operator+ (const Test& obj)" << endl;
return ret;
}
bool operator&& (const Test& obj)
{
cout << "bool operator&& (const Test& obj)" << endl;
return (i && obj.i);
}
};
int main(int argc, char *argv[])
{
Test t1 = 0;
Test t2 = 1;
if (t1 && (t1 + t2))
{
cout << "Hello Mr Tree!" << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
這裏輸出結果竟然是+操作和&&操作都執行了,爲什麼呢?我們把t1 && (t1 + t2)拆開來看就明白了,t1
&& (t1 + t2)實際上等價於t1.operator&&(t1.operator(t2)),所以說既然是函數調用,參數肯定是會先執行的,在這裏&&的短路性能就沒法體現了。