运算符重载

#include <iostream>

using namespace std;

class MyInt
{

private:
    /**********************加法重载*************************/
    friend MyInt operator+(const MyInt &a, const MyInt &b);
    friend ostream &operator<<(ostream &out, const MyInt &a);
    int val_;

public:
    explicit MyInt(int val) : val_(val) {}

    /*********************自增重载**************************/
    // 自增前缀
    MyInt &operator++()
    {
        val_++;
        return *this;
    }
    // 自增后缀
    MyInt operator++(int)
    {
        MyInt temp = *this;
        val_++;
        return temp;
    }

    /**************赋值运算符,拷贝构造************************/
    MyInt &operator=(int i)
    {
        cout << "assignments operator" << endl;
        val_ = i;
        return *this;
    }
    MyInt(const MyInt &o) : val_(o.val_)
    {
        cout << "copy constructor" << endl;
    }

    /********定义转换操作符int q = a;************/
    operator int()
    {
        return val_;
    }
};

MyInt operator+(const MyInt &a, const MyInt &b)
{
    return MyInt(a.val_ + b.val_);
}

ostream &operator<<(ostream &out, const MyInt &a)
{
    out << a.val_;
    return out;
}

int main()
{
    MyInt a(3), b(5);
    cout << a + b << endl;

    int q = a;
    cout << "q:" << q << endl;

    MyInt c(3);
    cout << c << "," << c++ << "," << c << endl;
    int i = 3;
    cout << i << "," << i++ << "," << i << endl;

    b = a;
    cout << "b:" << b << endl;

    b = 7;
    cout << "b:" << b << endl;

    MyInt d = a;
    cout << "d:" << d << endl;

    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务