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)),所以说既然是函数调用,参数肯定是会先执行的,在这里&&的短路性能就没法体现了。