1.算术/关系运算符
通常情况下,算术与关系运算符定义成非成员函数以允许左右侧运算对象进行转换。因为这些运算符一般不需要改变运算对象的状态,所以形参都是常量的引用。
以"+"号运算符为例:
Person operator+(const Person &p1, const Person &p2)
{
string s1(*p1.name);
string s2(*p2.name);
Person p;
p.age = p1.age + p2.age;
p.name = new string(s1+s2);
return p;
}
int main()
{
Person p1(20, "SCOTT");
Person p2(10, "Kate");
Person p3;
p3 = p1 + p2;
cout << p3 << endl;
return 0;
}
上面的函数应该定义为友元函数,因为直接用到了成员变量。
运行结果:
Init Person
Init Person
Default Person
Default Person
operator =
~Person name: 0x9087058 age: 30
p.age: 30, p.name: SCOTTKate
~Person name: 0x9087088 age: 30
~Person name: 0x9087048 age: 10
~Person name: 0x9087020 age: 20
可以看出,我们这里的+号操作,成功的讲两个人的年龄与姓名相加,最然这没有什么实际意义,但这里重在演示,相应的异常处理为节省时间也没加。
2.关系运算符
这里以==关系运算符为例:
bool operator==(const Person &p1, const Person &p2)
{
if(p1.age == p2.age && p1.name == p2.name)
{
return true;
}
return false;
}
int main()
{
Person p1(20, "SCOTT");
Person p2(10, "Kate");
Person p3;
if(p1 == p2)
{
cout << "p1 == p2" << endl;
}
else
{
cout << "p1 != p2" << endl;
}
return 0;
}
为了方便,直接判断的name,name是一个指针,按理说应该是*name 但这样就要加异常处理,也是为了节省时间。
运行结果:
Init Person
Init Person
Default Person
p1 != p2
~Person name: 0 age: 0
~Person name: 0x84fc048 age: 10
~Person name: 0x84fc020 age: 20
3.下标运算符
可以从容器中检索单个元素的容器类一般会定义下标操作符,即operator[]。如vector和string。
下标操作符必须定义为类成员函数。
类定义下标操作符时,一般需要定义两个版本:一个为非const成员并返回引用,另一个为const成员并返回引用!
给出一个简单的例子:
#include
#include
using namespace std; class Array { public: Array(int size) : _size(size) { _val = new int[_size]; } int& operator[] (int index) { return _val[index]; } const int& operator[] (int index) const { return _val[index]; } private: int _size; int *_val; }; int main() { Array a1(10); for(int i = 0; i<10; i++) { a1[i] = i; cout << a1[i] << endl; } const Array a2(100); for(int i = 0; i<100; i++) { // a2[i] = i; error read-only!!! cout << a2[i] << endl; } return 0; }