继承体制下二元操作符的重载

  C++Primer上建议最好把重载二元操作符函数作为非成员函数,我试验了下,代码如下,但有个问题,恳求得到诸位的回复。

代码
#include <iostream>
using namespace std;

class CPoint
{
public:
    CPoint(): fx(
0) { }
    CPoint(
float x): fx(x) { }
    
~CPoint() { }
protected:
    
public:
    
float fx;
};

class CPoint2d: public CPoint
{
public:
    CPoint2d(): fy(
0) { }
    CPoint2d(
float x, float y): CPoint(x), fy(y) { }

    
~CPoint2d() { }
protected:
    
public:
    
float fy;
};

inline 
bool operator==(const CPoint &lpt, const CPoint &rpt )
{
    cout 
<<"1d==" <<endl;
    
return lpt.fx == rpt.fx ? true : false;
}

inline 
bool operator!=(const CPoint &lpt, const CPoint &rpt )
{
    
return lpt == rpt ? false : true;
}

inline 
bool operator== (const CPoint2d &lpt, const CPoint2d &rpt )
{
    cout 
<< "2d==" <<endl;
    
if ( operator==(static_cast<CPoint>(lpt), static_cast<CPoint>(rpt) ) )
    {
        
if ( lpt.fy == lpt.fy )
        {
            
return true;
        }
    }

    
return false;
//    return operator==(lpt, rpt) && lpt.fy == rpt.fy ? true : false;
}

int main()
{
    CPoint pt1;
    CPoint pt2(
10);
    
    
if ( pt2 == pt1 )
    {
        cout 
<< "1d: Yes == " <<endl;
    }
    
else 
    {
        cout 
<< "1d: No != " <<endl;
    }

    CPoint2d pt2D;
    CPoint2d pt2D2(
510);

    
if ( pt2D == pt2D2 )
    {
        cout 
<< "2d: Yes == " <<endl;
    }
    
else
    {
        cout 
<< "2d: No != " <<endl;
    }

    cout 
<< pt2D.fx << " " <<pt2D.fy << " " << pt2D2.fx << " "<< pt2D2.fy <<endl;
    
return 0;
}

 

  输出如下:

1d==

1d:No !=

2d==

1d==

2d: No !=

0 0 5 10

Press any key to continue 

   我的问题在于给CPoint2d重载==操作符时,比较基类的部分,我想调用基类的==重载函数,但现在它不是成员函数,无法用CPoint::来指定调用基类,我想请问,有没有其他更好的方法使它跟是成员函数时一样好用?希望各位不吝赐教,可以讨论下你们的做法,O(∩_∩)O~,谢谢啦!

   

 

posted @ 2010-04-19 14:17  木叶道  阅读(280)  评论(0编辑  收藏  举报