《C++程序设计》教学讲义7章
第7章 运算符重载(operator)
§7.1 运算符重载概念
运算符重载是对已有的运算符赋予多重含义,
使同一个运算符作用与不同类型的数据导致不同类型的行为。
§7.2 运算符重载的规则
1、除少数几个外,其他运算符都可重载,且只能重载已有运算符。
注:不可重载的运算符,类属性关系运算符“.”,成员指针运算符“*”,
作用域分辨符“::”,sizeof运算符,三目运算符“?:”。
2、重载后,运算符的优先级和结合性保持不变。
3、重载运算符与原运算符功能相似,操作对象个数不变。
§7.3 运算符重载的两种形式
1、类的成员函数
一般语法:
返回值类型 operator 运算符(形参表)
{
函数体;
}
2、类的友元函数
一般语法:
friend 返回值类型 operator 运算符(形参表)
{
函数体;
}
§7.4 运算符重载——类成员函数
例题:
#include <iostream>
using namespace std;
class CPoint
{
public:
CPoint(int x, int y);
CPoint operator+(CPoint a);
void Show();
private:
int m_x;
int m_y;
};
CPoint::CPoint(int x, int y)
{
m_x = x;
m_y = y;
}
CPoint CPoint::operator+(CPoint a)
{
return CPoint(m_x+a.m_x, m_y+a.m_y);
}
void CPoint::Show()
{
cout<<"("<<m_x<<"."<<m_y<<")"<<endl;
}
int main()
{
CPoint a(2,3);
CPoint b(9,7);
CPoint c(0,0);
c = a+b;
c.Show();
return 0;
}
注:a+b 这里可以理解为 a.operator+(b);
例题:运算符“++”重载
#include <iostream>
using namespace std;
class CPoint
{
public:
CPoint(int x, int y);
CPoint operator++(); //++i
CPoint operator++(int); //i++
void Show();
private:
int m_x;
int m_y;
};
CPoint::CPoint(int x, int y)
{
m_x = x;
m_y = y;
}
CPoint CPoint::operator++()
{
return CPoint(++m_x, ++m_y);
}
CPoint CPoint::operator++(int)
{
return CPoint(m_x++, m_y++);
}
void CPoint::Show()
{
cout<<"("<<m_x<<"."<<m_y<<")"<<endl;
}
int main()
{
CPoint a(1,2);
CPoint b(0,0);
b = a++;
b.Show();
a.Show();
b = ++a;
b.Show();
a.Show();
return 0;
}
§7.5 运算符重载——类的友元函数
略