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

重载为成员函数:
一般情况下,当一元运算符的操作数,或者二元运算符的左操作数是该类的一个对象时 。
函数原型为:类名&类名::operator运算符(变量表)
例如:用重载函数实现字符串的连接(重载运算符“+”)
在这里插入代码片

#include “pch.h”
#include
#include
using namespace std;
class S
{ public:
S()
{
str = ‘\0; len = 0; //调用构造函数给变量置初值
}
S(const charpstr)
{
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++中不能,下列运算符不能重载为友元函数:
= () [ ] ->*

posted @ 2022-11-21 18:55  TwcatL_tree  阅读(4)  评论(0编辑  收藏  举报