运算符重载之何时重载为成员函数?何时重载为友元函数?

重载为成员函数:
一般情况下,当一元运算符的操作数,或者二元运算符的左操作数是该类的一个对象时 。
函数原型为:类名&类名::operator运算符(变量表)
例如:用重载函数实现字符串的连接(重载运算符“+”)
在这里插入代码片
#include “pch.h”
#include
#include
using namespace std;
class S
{ public:
S()
{
str = ‘\0’; len = 0; //调用构造函数给变量置初值
}
S(const char
pstr)
{
strcpy_s(str, pstr); len = strlen(pstr); //调用构造函数给变量赋值
}
char*gets()
{
return str; //返回字符串
}
int getLen()
{
return len; //返回字符串的长度
}
s&operator+(S obj); //声明重载运算符“+”函数
private:
char str[100];
int len;
};
S& S::operator+(S obj)
{
strcat_s(str, obj.str);
len = strlen(str);
return this;
} //重载运算符“+”的实现部分
int main()
{
S obj1(“Visual”), obj2(“C++”); //声明该类的对象同时调用相应的构造函数进行赋值
obj2 =obj1 + obj2;
cout << “obj2.str=” << obj2.gets() << endl;
cout << “obj2.len=” << obj2.getLen() << endl;
}
重载为友元函数
当运算符的左、右操作数类型不同时。
函数原型为:friend 类名 operator运算符(变量表)
注意:友元函数在类中的声明与定义是分开的,不可同时进行
例如:复数的加法运算
在这里插入代码片
#include “pch.h”
#include
#include
using namespace std;
class Complex
{
int real;
int image;
public:
Complex(){}
Complex(int a)
{
real = a;
image = 0;
}
Complex(int a, int b)
{
real = a;
image = b;
} //前三个均为构造函数
friend Complex operator+(Complex c1,Complex c2); //用友元函数重载“+”
void gets()
{
cout << “(” << real << “,” << image << “)” << endl; //输出结果
}
};
Complex operator+(Complex c1, Complex c2)
{
Complex c;
c.real = c1.real + c2.real;
c.image = c1.image + c2.image;
return c;
} //重载函数的定义
int main()
{
Complex c, c1(1, 2);
c = c1 + 1;
c.gets();
}
** 一般情况下,运算符都可重载为成员函数或友元函数,它们的关键区别在于,成员函数具有this 指针,而友元函数没有this指针。但在C++中不能,下列运算符不能重载为友元函数:
= () [ ] ->
*

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值