运算符重载注意事项
- C++ 几乎可以重载全部的运算符,而且只能够重载C++中已经有的。
- 不能重载的运算符: “.”、“.*”、“::”、“?:”
- 重载之后运算符的优先级、结合性、操作数个数、语法结构都不会改变。
- 重载为类的非静态成员函数、或非成员函数
- 基础数据类型之间的操作符无法重载,例如
Point operator + (int, int)
1 运算符重载为类外的非成员函数
cout << a << b
①operator << (cout, a)
即cout << a,a放入输出流,返回ostream的对象引用cout
②operator << (cout, a)
作为第二次调用的第一个参数,operator << ( operator << (cout, a) , b )
实现级联输出
#include <iostream>
using namespace std;
class Complex {
public:
Complex(int real, int imag) : real(real), imag(imag) {
cout << "调用Complex的构造函数" << endl;
}
friend Complex operator + (const Complex &c1, const Complex &c2);
friend Complex operator - (const Complex &c1, const Complex &c2);
friend ostream & operator << (ostream &out, const Complex &c1);
//Complex operator - (const Complex& c1);
private:
int real, imag;
};
Complex operator + (int a, const Complex& c1) {
//重载+号,左操作数为实数,右操作数为Complex类的常引用
return Complex(a+ c1.real, c1.imag);
}
Complex operator + (const Complex &c1, const Complex &c2) {
//重载为类成员函数可以达到同样效果
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
Complex operator - (const Complex &c1, const Complex &c2) {
//重载为类成员函数可以达到同样效果
return Complex(c1.real - c2.real, c1.imag - c2.imag);
}
ostream & operator << (ostream &out, const Complex &c1) {
//左操作数是ostream的引用,右操作数是Complex类的常引用
out << "实部:" << c1.real << " 虚部:" << c1.imag << endl;
return out; //返回ostream的引用
}
/* 重载为类成员函数可以达到同样效果
Complex Complex::operator - (const Complex& c1) {
return Complex(real - c1.real, imag - c1.imag);
}
*/
int main()
{
Complex c1(3, 4), c2(5, 6);
cout << (a + c2) << endl;
cout << (c1 + c2) << endl;
cout << (c2 - c1) << endl;
return 0;
}
输出结果:
调用Complex的构造函数
调用Complex的构造函数
调用Complex的构造函数
实部:55 虚部:6
调用Complex的构造函数
实部:8 虚部:10
调用Complex的构造函数
实部:2 虚部:2
当运算符同时重载为类成员函数和类外非成员函数,参数相同时,优先使用类成员函数