【十】运算符重载(上)

1、C++标准库

  • C++标准库并不是C++语言的一部分
  • C++标准库是由C++语言编写而成的类库和函数的集合
  • C++标准库中定义的类和对象都位于std命名空间中
  • C++标准库的头文件都不带.h后缀
  • C++标准库涵盖了C库的功能
  • C库中name.h头文件对应C++中的cname头文件
  • C++标准库预定义了多数常用的数据结构,如:字符串,链表,队列,栈等

示例:

一个类C风格的C++程序:

#include <cstdio>

using namespace std;

int main()
{
    printf("Hello World!\n");

    printf("Press any key to continue...\n");
    getchar();
    return 0;
}

一个C++“标准版”程序:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World!" << endl;

    cout << "Press any key to continue..." << endl;
    cin.get();
    return 0;
}

Tip:
这里写图片描述
思考:

左移运算符 << 和 右移运算符 >> 在C语言中只能用于整数运算,并且语义是确定不变的,C++是怎么改变左移运算符和右移运算符的语义的?

答案就是操作符重载!

 
 
2、操作符重载

操作符重载为操作符提供不同的语义

  • C++中通过operator关键字可以利用函数扩展操作符
  • operator的本质是通过函数重载实现操作符重载

示例:

#include <iostream>

using namespace std;

class Complex
{
private:
    int a;
    int b;
public:
    Complex(int i = 0, int j = 0)
    {
        a = i;
        b = j;
    }
    //如果没有友元函数的声明,在类外无法直接访问private成员
    friend Complex operator+ (const Complex& ra,const Complex& rb);
    friend ostream& operator<< (ostream& out, Complex& rc);
};

//“+”号运算符为双目运算符,所以重载参数有两个,且只能有两个,但是如果该重载函数为类的
//成员函数,那么就只能有一个显示的参数,因为会有一个隐藏的this指针参数
Complex operator+ (const Complex& ra,const Complex& rb)
{
    Complex ret;
    ret.a = ra.a + rb.a;
    ret.b = ra.b + rb.b;

    return ret;
}

//这里返回类型为ostream类对象的引用,是为了函数调用完成后,还能继续使用cout对象
//比如:cout << c3 << endl;  ==> (cout << c3) << endl;
//如果返回值不为ostream&,那么该调用会失败!
ostream& operator<< (ostream& out, Complex& rc)
{
    out<< rc.a << " + " << rc.b <<"i";

    return out;
}

int main()
{
    Complex c1(5,2);
    Complex c2(4,9);
    Complex c3 = c1 + c2;   //等价于:operator+(c1,c2);

    cout << c3 << endl;     //等价于:operator<<(cout,c3);

    cout << "Press any key to continue..." << endl;
    cin.get();
    return 0;
}

 
 
3、友元函数

C++中的类的友元函数

  • private声明使得类的成员不能被外界访问
  • 但是通过friend关键字可以例外的开放权限

 
 
4、小结

  • 操作符重载是C++的强大特性之一
  • 操作符重载的本质是通过函数扩展操作符的语义
  • operator关键字是操作符重载的关键
  • friend关键字可以对函数或类开发访问权限
  • 操作符重载遵循函数重载的规则
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值