6.14C++:运算符重载注意事项 、运算符重载为类外的非成员函数

运算符重载注意事项

  1. C++ 几乎可以重载全部的运算符,而且只能够重载C++中已经有的。
  2. 不能重载的运算符: “.”、“.*”、“::”、“?:”
  3. 重载之后运算符的优先级、结合性、操作数个数、语法结构都不会改变。
  4. 重载为类的非静态成员函数、或非成员函数
  5. 基础数据类型之间的操作符无法重载,例如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

当运算符同时重载为类成员函数和类外非成员函数,参数相同时,优先使用类成员函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值