• [C++]operator难点、豆知识


    operaotr除了用于重载=、>、<之类的东西外,还有以下用途

    1. 类型转换

    class T
    {
    public:
        operator int() const
        {
            return 5;
        }
    };

    上述的代码,为T类提供了转换为int的能力。默认隐式使用。注意使用了const,保证可靠性。

    T t = T();
    int i = t;
    cout << i << endl; // 输出5

    2. 赋值运算重载

    class T
    {    
    public:
        int _val;
        T(int val): _val(val){}
        void operator=(const T& t)
        {
            cout << "using operator=" << endl;
            _val = t._val;
        }
        operator int() const
        {
            return _val;
        }
    };
    
    int main()
    {
        // t1 构造函数初始化
        T t1 = T(1);
        // t2 使用了拷贝构造函数初始化
        T t2 = t1;
        // t3 初始化后,使用赋值语句
        T t3 = T(3);
        t3 = t1;
    
        int i1 = t1;
        int i2 = t2;
        int i3 = t3;
        cout << i1 << i2 << i3 << endl;
    
        system("pause");
    }

    可以重载operator=运算符,来实现类的赋值。但是不能实现级联赋值t3 = t2 = t1,需要修改operator=为

    T& operator=(const T& t)
    {
        cout << "using operator=" << endl;
        _val = t._val;
        return *this;
    }
  • 相关阅读:
    OpenCV中threshold函数的使用
    opencv中namedWindow( )函数
    Open CV leaning
    RGB颜色表
    visual studio 2015 Opencv4.0.1配置
    uint16_t
    Arduino重置-复位问题
    bzoj1823 [JSOI2010]满汉全席(2-SAT)
    bzoj2208 [Jsoi2010]连通数(scc+bitset)
    UVAlive3713 Astronauts(2-SAT)
  • 原文地址:https://www.cnblogs.com/SelaSelah/p/2468502.html
Copyright © 2020-2023  润新知