王老师 C++ 运算符重载 转换函数 第一讲

运算符函数:operator 运算符

运算符重载,两种方式:

a.成为成员函数

b.名字空间函数(友元函数)

不能重载的运算符有: ::, ., .*, ?:

必须重载为成员函数的运算符: [], (), ->, =

要求:

a.不能引进新运算符

b.不改变元数,优先级,结合性。

定义语法:

二元函数

值类型 operatoe◎(类型名 形参名) 函数体 // 成员函数

值类型 operatoe◎(类型名 形参名, 类型名 形参名) 函数体 // 全局函数

一元函数

值类型 operatoe◎() 函数体 // 成员函数

值类型 operatoe◎(类型名 形参名) 函数体 // 全局函数

例子程序:

#include <iostream>
using namespace std;

class com{
private:
 int real;
 int img;

public:
 com(int real = 0, int img = 0){
  this->real = real;
  this->img = img;
 }

 void com_add(com &x, com &y, com &z){
  z.real = x.real + y.real;
  z.img = x.img + y.img;
 }
 
 com operator + (com x){
  return com(this->real + x.real, this->img + x.img);
 }
 
 /*
 com operator + (com & x){
  return com(this->real + x.real, this->img + x.img);
 }
 */
 
 /*
 //warning C4172: returning address of local variable or temporary
 com & operator + (com & x){
  return com(this->real + x.real, this->img + x.img);
 }
 */

 com operator + (int x){
  return com(this->real + x, this->img);
 }

 friend com operator + (int x, com y);

 void show(){
  cout << real <<  "," << img << endl;
 }

};

com operator +(int x, com y){
 return com(x + y.real, y.img);
}

int main()
{
 com a, b(1, 2), c(2, 3);
 a = b + c;
 a.show();

 a.com_add(b, c, a);
 a.show();

 a = b + 3;
 a.show();

 a = 3 + c;
 a.show();

}

注意:com & operator + (com & x)

在类成员函数中重载运算符是不允许返回引用的,会出现“返回局部变量的地址”警告。

但是对于函数 void com_add(com &x, com &y, com &z)则可以。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值