다음 코드를 이와 같이 수정할 수 있습니다. 주 기능에서 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;
}
추천 읽기 : http://stackoverflow.com/questions/4421706/operator-overloading –
간단히 요약하면 + =, - =, * = 및/=와 거의 비슷한 동작을하는 연산자를 작성한 것입니다. 원하는 것을 얻으려면 +, -, * 및/또는처럼 작동하는 연산자가 필요합니다. – Hurkyl
들여 쓰기. ** please. ** –