2014-10-01 2 views
-2
#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; 
} 

위 코드에서는 멤버 함수로 연산자 오버로딩을 구현할 수 있습니다. 그러나 비 멤버 함수로 연산자 오버로딩을 구현하지 못했습니다. 이 코드를 어떻게 수정해야합니까 bb 도와주세요 ..멤버 함수에서 비 멤버 함수로 코드 변환

+2

관련 코드를 표시하고 관련없는 코드를 제거하는 것이 좋습니다. – juanchopanza

+1

실패한 시도의 코드는 어디에 있습니까? –

+0

'return weight == b.weight;''=='와'double '을 비교하지 마십시오. –

답변

1

기본적으로 멤버 함수와 비 멤버 함수의 유일한 차이점은 암시 적 this 포인터와 다른 인수가 전달되어 액세스 할 수 있다는 것입니다 ~ private/protected 회원. 따라서 멤버 함수를 비 멤버 함수로 변환하는 것은 정의를 class 정의에서 제외하는 것입니다. 그 클래스의 friend으로 만들고 해당 클래스에 대한 참조 인 매개 변수를 추가하십시오. 호출 할 때 해당 클래스의 객체를 전달하십시오. 함수의 const&을 수행 할 수도 있습니다.

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(); 
} 
0

당신은 친구 기능을 사용하고 우리가 < < 연산자에서 사용하는 것처럼 그 함수의 매개 변수로 개체를 사용할 수 있습니다. 친구 기능이없는 연산자도 사용할 수 있습니다.

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