C + + input, output operator overloading

Source: Internet
Author: User

C + + can use stream extraction operators >> and stream insert operators << to enter and output built-in data types. We can overload the stream extraction operator and the stream insert operator to manipulate user-defined data types such as objects.

Here, it is important to declare the operator overload function as a friend function of the class, so that we can directly invoke the function without creating the object.
The following example shows how to overload the extract operator >> and insert operator <<.

#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 + + input, output operator overloading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.