[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;
}

 

 

posted @ 2012-04-24 18:14  斯啦丝拉  阅读(306)  评论(0编辑  收藏  举报