将代码从成员函数转换为非成员函数

时间:2014-10-01 15:38:32

标签: c++

#include <iostream>
using namespace std;

class family
{
private:
    double weight;
    double height;
public:
    family(double x,double y); 
    ~family();
    double getWeight();
    double getHeight();
    double setWeight();
    double setHeight();
    bool operator==(const family &)const; 
};

bool family::operator ==(const family &b)const
{
         return weight==b.weight;
}     

family::family(double x, double y)
{
    weight = x;
    height = y;
}

double family::getWeight()
{
    return weight;
}

double family::getHeight()
{
    return height;
}

family::~family(){}

int main()
{
 family a(70.0,175.2);
 family b(68.5,178.2);

 if(a==b)
 cout << "A is bigger than B" << endl;
 else
 cout << "A is smaller than B" << endl;

return 0;
}

在代码之上,我可以用成员函数实现运算符重载。但是,我无法使用非成员函数实现运算符重载。我该如何修改这个代码b.b. 请帮帮我..

3 个答案:

答案 0 :(得分:1)

基本上,成员函数和非成员函数之间的唯一区别是它传递了一个隐式this指针以及任何其他参数,并且它可以访问private/protected成员。因此,将任何成员函数转换为非成员函数只是将其从class定义中分解出来。使其成为该类的friend并添加一个参数,该参数是该类的引用。在调用它时传入该类的对象。您还可以执行该功能的const&

答案 1 :(得分:0)

class family
{
private:
    double weight;
    double height;
public:
    family( double x, double y );
    ~family( );

    // getters should be const
    double getWeight( ) const;
    double getHeight( ) const;
    double setWeight( );
    double setHeight( );
};
// no reason to make it friend of class
// b/c it does not work with private/protected members 
bool operator==( const family & first, const family & second );

// better to move into cpp file
bool operator==( const family & first, const family & second )
{
    return first.getWeight( ) == second.getWeight( );
}

答案 2 :(得分:0)

你可以使用Friend Function并使用对象作为该函数的参数,就像我们在&lt;&lt;运营商。 我们也可以使用没有朋友功能的操作员:

bool operator==(const family first, const family second) 
{
if(first.getWeight( ) == second.getWeight( )){
return True;
else
 return False;
}