1. 输出运算符重载

1.1 简介

输出运算符重载,实际上是 << 的重载。 << 实际上是位移运算符,但是在c++里面,可以使用它来配合cout在控制台打印输出。 cout 其实是ostream 的一个实例,而ostrem 是 类basic_ostream的一个别名, basic_ostream里面对 << 运算符进行了重载,能使用cout << 来输出内容

1.2 来源

#include <iostream>

using namespace std;

class stu {
public :
    string name;
    int age;
    stu(string name , int age):name(name) , age(age){}
};


int main() {
    stu s("王腾" , 16);
    cout << s.name << " : " << s.age <<endl;

    cout << 18; // operator<<(int n);
    cout << "王腾"; // operator<<(char n);

    return 0;
}

coutbasic_ostream类的一个对象,它的后面跟上一个 << 符号,实际上就是调用了 basic_ostream 这个类里面的一个函数 , 函数是: operator<<()

using ostream       = basic_ostream<char, char_traits<char>>;
class basic_ostream;

cout << s; 也就是 operator<<(stu s);,直接输出对象,那么需要重载 << 符号,因为标准库里面没有 stu 类,同时不建议去修改cout对应的类的源码,所以应该使用全局的方式定义

1.3 全局定义

#include <iostream>

using namespace std;

class stu {
public :
    string name;
    int age;
    stu(string name , int age):name(name) , age(age){}
};

ostream& operator<<(ostream &  os, stu & s){
    os << s.name << "  " <<s.age <<endl;
    return os;
}

int main() {
    
    stu s0("王腾" , 16);
    stu s1("华云飞" , 17);

    cout << s0 << s1 ;

    return 0;
}

全局的定义方式重载 << :

void operator<<(ostream &  os, stu & s)

第一个参数是 cout 对象,第二个参数是要打印的对象,返回值 void,如果要链式调用,返回值是 cout 对象
第一个参数必须要加上 & 变成引用的类型,因为cout对象的类禁止拷贝
第二个参数加不加都可以,加上的话不会开辟新的空间。
返回值一定得是引用类型,因为cout对象禁止拷贝

2. 输入运算符重载

输入运算符重载,实际上就是 >> 的重载,用法和上面的输出运算符重载相似

#include <iostream>

using namespace std;

class stu {
public :
    string name;
    int age;

    stu(){};
    stu(string name , int age):name(name) , age(age){}
};



ostream& operator<<(ostream &  os, stu & s){
    os << s.name << "  " <<s.age <<endl;
    return os;
}

istream& operator>> (istream& in, stu &s1) {
    in >> s1.name >> s1.age;

    return in;
}


int main() {

    stu s1;

    cout << "请输入学生的姓名和年龄:" << endl;
    cin >>  s1;

    //打印学生, 实际上是打印他的名字。
    cout << s1  <<endl ;
    return 0;

    return 0;
}

运行过程:

请输入学生的姓名和年龄:
王腾
12
王腾  12

3.赋值运算符重载

10-16 08:30