C++讲义 第7章 运算符重载(operator)

《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 运算符重载——类的友元函数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值