美文网首页
运算符重载

运算符重载

作者: 李永开 | 来源:发表于2021-07-24 14:13 被阅读0次

    一.+号运算符重载

    //
    //  main.c
    //  cdemo
    //
    //  Created by liyongkai on 2021/6/6.
    //
    
    #include <iostream>
    using namespace std;
    
    class Person{
    public:
        int a;
        int b;
        Person(){};
        Person(int a, int b):a(a), b(b) {
        };
        
        //+号运算符重载
        Person operator+(Person &p) {
            Person temp;
            temp.a = this->a + p.a;
            temp.b = this->b + p.b;
            return temp;
        };
    };
    
    
    int main(int argc, const char * argv[]) {
        
        Person p1 = Person(1,2);
        Person p2(10, 10);
        
        Person p3 = p1 + p2;
        cout << "a:" << p3.a << "   " << "b:" << p3.b << endl;
        //a:11   b:12
    
        return 0;
    }
    

    二.<<号运算符重载

    //
    //  main.c
    //  cdemo
    //
    //  Created by liyongkai on 2021/6/6.
    //
    
    #include <iostream>
    using namespace std;
    
    class Person{
    public:
        int a;
        int b;
    };
    
    ostream& operator<<(ostream &cout, Person &p) {
        cout << "a:" << p.a;
        return cout;
    }
    
    int main(int argc, const char * argv[]) {
        
        Person p1;
        p1.a = 10;
        cout << p1 << endl;//a:10
    
        return 0;
    }
    

    三.指针运算符重载(智能指针)

    相关文章

      网友评论

          本文标题:运算符重载

          本文链接:https://www.haomeiwen.com/subject/muxvmltx.html