类的operator +操作符满足交换律

来源:互联网 发布:淘宝开店新手入门 编辑:程序博客网 时间:2024/06/03 21:03

例如Spreadsheetcell(单元格)

      若operator +作为类的成员函数,因为operator +方法必须Spreadsheetcell对象上调用,对象必须在operator +的左边,

若遇到athirdCell= mycell+4;可以编译,但是athirdCell=4+mycell则通不过编译。

想要解决这个问题,需要通过全局的operator +

const  Spreadsheetcell operator +(const  Spreadsheetcell &lhs , const  Spreadsheetcell& rhs)

{

        Spreadsheetcell   newCell;

        newCell.set(lhs.mValue+rhs.mValue);

        return newCell;

}


若operator +访问了Spreadsheetcell Spreadsheetcell operator +需要时Spreadsheetcell 类的友元函数;

class  Spreadsheetcell 

{

public :

    friend  const  Spreadsheetcell operator +(const  Spreadsheetcell &lhs , const  Spreadsheetcell& rhs);

}

0 0
原创粉丝点击