[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
  1. 赋值运算重载
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;
}

原文链接: https://www.cnblogs.com/SelaSelah/archive/2012/04/24/2468502.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/48374

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午12:13
下一篇 2023年2月9日 上午12:13

相关推荐