运算符重载到底以成员函数的形式更好还是全局函数(友元函数)的形式更好
注意:
C++ 规定,箭头运算符->、下标运算符[ ]、函数调用运算符( )、赋值运算符=只能以成员函数的形式重载。
1.全局函数的形式重载 +、-、*、/、==、!=
例:假设以成员函数的方式重载 + (这是错误的)
#include <iostream>
using namespace std;
//复数类
class Complex {
public:
Complex() : m_real(0.0), m_imag(0.0) { }
Complex(double real, double imag) : m_real(real), m_imag(imag) { }
Complex(double real) : m_real(real), m_imag(0.0) { }
public:
Complex operator+(const Complex& c1)const;
public:
double real() const { return m_real; }
double imag() const { return m_imag; }
private:
double m_real; //实部
double m_imag; //虚部
};
Complex Complex::operator+(const Complex& c1)const {
Complex c3;
c3.m_real = this->m_real + c1.m_real;
c3.m_imag = this->m_imag + c1.m_imag;
return c3;
}
int main() {
Complex c1(25, 35);
Complex c2 = c1 + 15.6;
cout <<"c2" << c2.real() << " + " << c2.imag() << "i" << endl;
// Complex c3 = 15.6 + c1;
// cout <<"c3" << c3.real() << " + " << c3.imag() << "i" << endl;
return 0;
}
上述代码执行Complex c2 = c1 + 15.6;
编译器检测到+号左边(+号具有左结合性,所以先检测左边)是一个 complex 对象,就会调用成员函数operator+()。检测到15.6是一个double。于是自动调用Complex(double real)这个转换构造函数。最后执行成功。
但是如果执行Complex c3 = 15.6 + c1;
就会发生错误了,因为 double 类型并没有以成员函数的形式重载 +。
也就是说,以成员函数的形式重载 +,只能计算c1 + 15.6,不能计算15.6 + c1。
C++ 只会对成员函数的参数进行类型转换,而不会对调用成员函数的对象进行类型转换
改为全局函数(友元函数):
#include <iostream>
#include"test1.h"
using namespace std;
//复数类
class Complex {
public:
Complex() : m_real(0.0), m_imag(0.0) { }
Complex(double real, double imag) : m_real(real), m_imag(imag) { }
Complex(double real) : m_real(real), m_imag(0.0) { }
public:
friend Complex operator+(const Complex& c1, const Complex& c2);
public:
double real() const { return m_real; }
double imag() const { return m_imag; }
private:
double m_real; //实部
double m_imag; //虚部
};
Complex operator+(const Complex& c1, const Complex& c2) {
Complex c;
c.m_real = c1.m_real + c2.m_real;
c.m_imag = c1.m_imag + c2.m_imag;
return c;
}
int main() {
Complex c1(25, 35);
Complex c2 = c1 + 15.6;
cout <<"c2" << c2.real() << " + " << c2.imag() << "i" << endl;
Complex c3 = 15.6 + c1;
cout <<"c3" << c3.real() << " + " << c3.imag() << "i" << endl;
return 0;
}
这样就可以了。
所以建议以全局函数的形式重载 +、-、*、/、==、!= 这类左右数据类型可颠倒的运算符
2.以成员函数的形式重载 +=、-=、*=、/=
因为 += 符号不存在有数据类型颠倒的情况,且
运算符重载的初衷是给类添加新的功能,方便类的运算,所以这类运算符首选用类的成员函数去重载。