2011-12-11 2 views
0

다음 코드를 이와 같이 수정할 수 있습니다. 주 기능에서 f2=11; f3=12;을 반복 할 필요가 없습니다. 이 코드는 가장 일반적인 연산자를 오버로드하는 데 사용됩니다.클래스 객체를 사용하는 오버로드 연산자는 무엇입니까?

class FLOAT{ 
    private: 
     float x; 
    public: 
     FLOAT(){ x=0.0; } 
     void setFloat(float f)  { x=f; } 
     float getFloat()   { return x;}; 
     FLOAT operator+(FLOAT obj) {x=x+obj.x; return *this;}; 
     FLOAT operator-(FLOAT obj) {x=x-obj.x; return *this;}; 
     FLOAT operator*(FLOAT obj) {x=x*obj.x; return *this;}; 
     FLOAT operator/(FLOAT obj) {x=x/obj.x; return *this;}; 
     FLOAT& operator=(const FLOAT& obj) {this->x=obj.x; return *this; }; 
     FLOAT& operator=(const float& y) {this->x=y; return *this; }; 
}; 

int main() { 
    FLOAT f,f2,f3; 
    f2=11; 
    f3=12; 

    f=f3-f2; 
    cout<<"f3-f2 ="<<f.getFloat()<<endl; 


    f2=11; 
    f3=12; 
    f=f3+f2; 
    cout<<"f3+f2 ="<<f.getFloat()<<endl; 

    f2=11; 
    f3=12; 
    f=f3*f2; 
    cout<<"f3*f2 ="<<f.getFloat()<<endl; 

    f2=11; 
    f3=12; 
    f=f3/f2; 
    cout<<"f3/f2 ="<<f.getFloat()<<endl; 

    system("pause"); // to pause console screen 
    return 0; 
} 
+2

추천 읽기 : http://stackoverflow.com/questions/4421706/operator-overloading –

+1

간단히 요약하면 + =, - =, * = 및/=와 거의 비슷한 동작을하는 연산자를 작성한 것입니다. 원하는 것을 얻으려면 +, -, * 및/또는처럼 작동하는 연산자가 필요합니다. – Hurkyl

+0

들여 쓰기. ** please. ** –

답변

3

@ 올리의 대답은 거의 당신이 무엇을 말합니까 최소 코드 작업을하기 위해해야 ​​할 일. 그러나 클래스의 구현에는 많은 결함이 있다는 것을 알았습니다 (@Oli도 알고 있음).

FLOAT을 구현 했으므로 Double (구현은 FLOAT과 비슷합니다)을 설명합니다. 당신이 operator=(Double const&)Double(Double const&)를 구현할 필요가 없습니다

class Double { 
    double data; 
public: 
    Double (double p=0.0) : data(p){} 
    double value() { return data; } 
    Double & operator+=(Double const & other) 
    { 
     data += other.data; 
     return *this; 
    } 
    Double & operator-=(Double const & other) 
    { 
     data -= other.data; 
     return *this; 
    } 
    //... 
}; 

참고. 컴파일러가 생성 한 컴파일러만으로 충분할 것입니다. 생성자가 double 유형의 인수를 하나씩 사용하므로 operator=(double const &)도 구현할 필요가 없습니다. 컴파일러는 생성자와 함께 복사 의미론을 생성하여이를 처리합니다.

지금, 나는 각각 operator+=operator-=의 측면에서 operator+operator-을 구현했습니다

//implement operator+ and operator- as non-member functions 
Double operator+(Double a, Double const & b) 
{ 
    a += b; //a is local copy, so we can change it 
    return a; 
} 
Double operator-(Double a, Double const & b) 
{ 
    a -= b; //a is local copy, so we can change it 
    return a; 
} 

참고이를 참조하십시오.

마찬가지로, 당신은 그들의 관점에서 operator/operator*을 구현 한 후 멤버 함수로 operator/=operator*=을 구현 할 수 있습니다!

2

운영자는 새 인스턴스를 만들어야합니다. 그들은 스스로 수정해서는 안됩니다 (실제로 이것을 막기 위해 const으로 선언해야합니다).

예컨대 :

FLOAT operator+(FLOAT obj) const 
{ 
    FLOAT tmp; 
    tmp.setFloat(x + obj.x); 
    return tmp; 
} 

주 (예컨대 operator+= 환산 operator+를 형성하고 float 소요 생성자 정의) 연산자 과부하를 정의 더욱 관용적 인 방법이있다. 그러나 위는 충분해야합니다.

+0

'FLOAT (float a_x)'생성자를 추가하면 다음과 같이 향상됩니다 :'FLOAT operator + (FLOAT obj) const {return FLOAT (x + obj.x); }' – hmjd

관련 문제