操作符重载上

C++标准库并非C++语言一部分,其为由C++语言编写而成的类库和函数的集合,位于std命名空间中,头文件不带.h后缀,C++标准库涵盖了C库的所有功能,C库中<name.h>头文件对应C++中<cname>
C++标准库预定义了多数常用数据结构,如字符串、链表、队列、栈等
<bitset><deque><list><map><queue><set><stack><vector>
C++标准库中显示器对象cout、键盘对象cin
C++怎么改变左移运算符和右移运算符语义?重载
操作符重载为操作符提供不同语义
------/例:复数相加
Complex add(const Complex& c1, const Complex& c2)
{
    Complex ret;
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    return ret;
}
add函数可解决复数相加问题,但为何不让+操作符也支持复数相加呢?
C++可通过operator关键字利用函数扩展操作符,本质重载
struct Complex
{
    int a;
    int b;
};
Complex operator+(const Complex& c1, const Complex& c2)
{
    Complex ret;
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    return ret;
}
int main(int argc, char *argv[])
{
    Complex c1 = {1, 2};
    Complex c2 = {3, 4};
Complex c3 = c1+c2; 	//也可写为Complex c3 = operator+(c1,c2);
					//本质函数调用
    cout<<"c3.a = "<<c3.a<<endl;	//4
    cout<<"c3.b = "<<c3.b<<endl;	//6
    return EXIT_SUCCESS;
}

------/ operator关键字扩展操作符用于类

#include <cstdlib>
#include <iostream>
using namespace std;
class Complex
{
    int a;
    int b;
public:
    Complex(int a = 0, int b = 0)	//参数默认值 
    {
        this->a = a;
        this->b = b;
    }
    int getA()
    {
        return a;
    }
    int getB()
    {
        return b;
}
	friend ostream& operator<< (ostream& out, const Complex& c);
    friend Complex operator+ (const Complex& c1, const Complex& c2);
};

ostream& operator<< (ostream& out, const Complex& c)
{
    out<<c.a<<" + "<<c.b<<"i";
    return out;
}

Complex operator+(const Complex& c1, const Complex& c2)
{	//为类外部全局函数,不能直接访问类private成员a、b 
    Complex ret;
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    return ret;
}

int main(int argc, char *argv[])
{
    Complex c1(1, 2);
    Complex c2(3, 4);
Complex c3 = c1 + c2;
	cout<<c1<<endl;
	cout<<c2<<endl;
	cout<<c3<<endl;
    return EXIT_SUCCESS;
}

类的友元:private声明使得类成员不被外界访问,friend关键字可开放权限
ostream& operator<< (ostream& out, const Complex& c);为何返回ostream&?
改为cout<<c1,输出1+2i无换行,变换表达方法为operator<<(cout,c1),输出1+2i无换行,将函数改为void operator<< (ostream& out, const Complex& c),输出1+2i无换行,但无返回导致无法支持链式调用,因cout<<c1<<endl等价operator<<(cout,c1) <<endl等价void <<endl

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值