- 1. 语法格式
- 1.1 友元重载
- 1.2 成员重载
- 1.3 注意事项
- 2. 重载规则
- 3. 双目运算符重载
- 3.1 成员函数重载+=实现
- 3.2 友元函数重载+=实现
- 4. 单目运算符重载
- 4.1 友元函数重载++(前++)实现
- 4.2 友元函数重载++(后++)实现
- 4. 友元还是成员
运算符重载的本质是函数重载。 1. 语法格式
返值类型 operator 运算符名称(形参表列)
{
重载实体;
}
operator 运算符名称 在一起构成了新的函数名。比如
const Complex operator+(const Complex &c1,const Complex &c2);
我们会说,operator+ 重载了重载了运算符+。
#includeusing namespace std; class Complex { public: Complex(float x=0, float y=0):_x(x),_y(y){} void dis() { cout<<"("<<_x<<","<<_y<<")"< 1.2 成员重载 #include1.3 注意事项using namespace std; class Complex { public: Complex(float x=0, float y=0):_x(x),_y(y){} void dis() { cout<<"("<<_x<<","<<_y<<")"< _x + another._x,this->_y + another._y); } int main() { Complex c1(2,3); Complex c2(3,4); c1.dis(); c2.dis(); // Complex c3 = c1+c2; // Complex c3 = operator+(c1,c2); Complex c3 = c1+c2; //优先调用成员函数重载?? c3.dis(); return 0; } 关于运算符重载函数的返回值:
2. 重载规则
int a = 3;
int b = 4;
(a+b) = 100; 这种语法是错的,所以重载函数+的返回值加 const 是来修饰。
string a = “china”,b = “ is china”, c;
(c = a) = b; 此时的语法,是重载= 返回值不需加 const 。3. 双目运算符重载 3.1 成员函数重载+=实现
- C++不允许用户自己定义新的运算符,只能对已有的 C++运算符进行重载。
- C++允许重载的运算符
- 不能重载的运算符
- 重载不能改变运算符运算对象(即操作数)的个数。
- 重载不能改变运算符的优先级别。
- 重载不能改变运算符的结合性。如,复制运算符”=“是右结合性(自右至左),重载后仍为右结合性。
- 重载运算符的函数不能有默认的参数,否则就改变了运算符参数的个数,与前面矛盾。
- 重载运算符的运算中至少有一个操作数是自定义类。重载的运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应有一个是类对象(或类对象的引用)。也就是说,参数不能全部是 C++的标准类型,以防止用户修改用于标准类型数据成员的运算符的性质。
using namespace std; class Complex { public: Complex(float x=0, float y=0):_x(x),_y(y){} void dis() { cout<<"("<<_x<<","<<_y<<")"<_x += c._x; this->_y += c._y; return * this; } private: float _x; float _y; }; int main() { int a = 10, b = 20,c = 30; (a += b) += c; cout<<"a = "< 3.2 友元函数重载+=实现 friend Complex& operator-=(Complex &c1, const Complex & c2) { }4. 单目运算符重载 4.1 友元函数重载++(前++)实现#includeusing namespace std; class Complex { public: Complex(float x=0, float y=0):_x(x),_y(y){} void dis() { cout<<"("<<_x<<","<<_y<<")"< 4.2 友元函数重载++(后++)实现 #includeusing namespace std; class Complex { public: Complex(float x=0, float y=0):_x(x),_y(y){} void dis() { cout<<"("<<_x<<","<<_y<<")"< 4. 友元还是成员 1,一个操作符的左右操作数不一定是相同类型的对象,这就涉及到将该操作符函数定义为谁的友元,谁的成员问题。
2,一个操作符函数,被声明为哪个类的成员,取决于该函数的调用对象(通常是左操作数)。
3,一个操作符函数,被声明为哪个类的友员,取决于该函数的参数对象(通常是右操作数)。假设,我们有类 Sender 类和 Mail 类,实现发送邮件的功能
Sender sender; Mail mail; sender<< mailsender 左操作数,决定了 operator<<为 Sender 的成员函数,而 mail 决定了operator<<要作 Mail 类的友员。
#includeusing namespace std; class Mail; class Sender { public: Sender(string s):_addr(s){} Sender& operator<<(const Mail & mail); //成员 private: string _addr; }; class Mail { public: Mail(string _t,string _c ):_title(_t),_content(_c){} friend Sender& Sender::operator<<(const Mail & mail); //友元 private: string _title; string _content; }; Sender& Sender::operator<<(const Mail & mail) { cout<<"Address:"<<_addr<



