C++重载运算符由两种方法:
1,直接将运算符函数重载为类内成员函数
2,将运算符函数重载为类的友元函数
以下为operator+的运算符函数,并且两种方法都可以实现连+;
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Op
{
public:
Op(const string& str);
~Op();
void print() const {
cout << m_str << endl;
};
//Op operator+(const Op& op);//方法1
friend Op operator+(const Op& op1, const Op& op2);//方法2
private:
string m_str;
};
Op::Op(const string& str)
{
m_str = str;
}
//Op Op::operator+(const Op& op)//方法1
//{
// Op retOp(m_str);
// retOp.m_str.append(op.m_str);//从这里看出C++的私有变量是可以被同类的其他实例访问的!
// return retOp;
//}
Op operator+(const Op& op1, const Op& op2)//方法2
{
Op retOp(op1.m_str);
retOp.m_str.append(op2.m_str);//friend函数可以访问私有变量
return retOp;
}
Op::~Op()
{
}
int main()
{
Op op1("123");
Op op2("456");
Op op3("789");
Op op4 = op1 + op2 + op3;
op4.print();
return 0;
}
其中方法1为类的成员函数重载运算符,a+b可以理解为普通的成员函数调用:a.operator(b)。
一般情况下,两种方式都可以,但是在某些特殊的情况下,不能将运算符重载为类内成员。原因在于,比如a.operator(b),其中a必须是类的一个实例,但有的时候可能无法满足这个情况,最常见的比如:
1,字符串“123”+str;
C++有时会隐式调用符合参数的构造函数,例如str+”123”,编译器检测到str是一个string类型,而运算符+只有string+string的重载函数,此时会将“123”构造成string(“123”),等同于str+string(“123”)。但是如果反过来写“123”+str。编译器无法推测出需要将“123”构造成string,甚至编译器根本不知道你调用的是哪个函数,因此无法通过编译!这时智能用友元函数重载+操作。“123”+str将调用 oprator+(string,string),编译器很容易推测出需要隐式构造。(C++普通函数也有类似的推测机制)
2,std::cout<
A A::operator++()//a++
{
...
}
A A::operator++(int)//++a 无名参数int知识告诉编译器这个是前缀++
{
...
}
下面[]操作的运算符重载
char& String::operator[](int n)
{
...
}
const char& String::operator[](int n) const
{
...
}
有时操作符重载会影响STL的调用,参见此博文:https://blog.youkuaiyun.com/h258384667/article/details/51728355