设为首页 加入收藏

TOP

C++ 输入、输出运算符重载
2018-03-02 06:57:05 】 浏览:129
Tags:输入 输出 运算 重载

C++ 能够使用流提取运算符 >> 和流插入运算符 << 来输入和输出内置的数据类型。我们可以重载流提取运算符和流插入运算符来操作对象等用户自定义的数据类型。


在这里,有一点很重要,我们需要把运算符重载函数声明为类的友元函数,这样我们就能不用创建对象而直接调用函数。


下面的实例演示了如何重载提取运算符 >> 和插入运算符 <<。


#include <iostream>


using namespace std;


class Person{
public:
    Person(const char *str) : name(str){}
   
    int GetAge(){
        return this->age;
    }
   
    /* 声明为类的友元函数 */
    friend ostream& operator<<(ostream& output, Person &p){
        output << p.name << endl;
        return output;
    }
   
    friend istream& operator>>(istream& input, Person &p){
        input >> p.age;
        return input;
    }
   
private:
    const char *name;
    int age;
};


int main()
{
    Person p("Tom");
   
    /* 重载输出名字 */
    cout << p;
   
    /* 重载输入年龄 */
    cin >> p;
   
    /* 输出年龄 */
    cout << p.GetAge() << endl;
   
    return 0;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇关于 C++ 日期 & 时间 初入门 下一篇Uboot 引导内核时加载地址与入口..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目