복잡한 코드를 처리하기 위해 C++로 코드를 작성하고 있습니다. 나는 또한 연산자 오버로드도 연습하고 있었다. 그래서 *
(곱셈 연산자)를 오버로드했습니다. 이제 오버로드 된 연산자를 /
(나누기 연산자)에서 오버로드 한 연산자를 사용하고 싶습니다. 그러나 *
을 사용할 때 오류가 나타납니다.같은 클래스의 다른 연산자 오버로딩 멤버 함수에서 연산자 오버로드 된 멤버 함수를 호출하거나 (또는 연산자를 사용할 수 있습니까?
#include <iostream>
#include <cmath>
using namespace std;
class Imaginary
{
public:
//constructors
Imaginary(double a,double b):x(a),y(b){}
Imaginary():x(0.0),y(0.0){}
//setter methods for x and y
void Setx(double x) { this->x = x; }
void Sety(double y) { this->y = y; }
//getter methods for x and y
double Getx(){return this->x;}
double Gety(){return this->y;}
//overloaded operators
Imaginary operator+(Imaginary&);
Imaginary operator-(Imaginary&);
Imaginary operator*(Imaginary&);
Imaginary operator~();
Imaginary operator/(Imaginary&);
void print();
private:
double x;
double y;
};
Imaginary Imaginary::operator+(Imaginary &i){
Imaginary ti;
ti.Setx(this->x+i.x);
ti.Sety(this->y+i.y);
return ti;
}
Imaginary Imaginary::operator-(Imaginary &i){
Imaginary ti;
ti.Setx(this->x-i.x);
ti.Sety(this->y-i.y);
return ti;
}
Imaginary Imaginary::operator*(Imaginary &i){
Imaginary ti;
ti.Setx((this->x*i.x) - (this->y*i.y));
ti.Sety((this->y*i.x)+(this->x*i.y));
return ti;
}
Imaginary Imaginary::operator~(){
int y;
y = this->y;
this->y = -y;
return *this;
}
Imaginary Imaginary ::operator/(Imaginary &i){
Imaginary numerator,denominator,ti;
//i want to use here the overloaded *(multiplacation) operator
numerator = (*this) * (~i);//showing error
denominator = (*this) * (~i);//showing error
ti.Setx(numerator.Getx()/denominator.Getx());
ti.Sety(numerator.Gety()/denominator.Getx());
return ti;
}
void Imaginary::print(){
cout<<x;
if (y>0)
cout<<"+i"<<y<<endl;
else if (y<0)
cout<<"-i"<<abs(y)<<endl;
}
int main()
{
Imaginary res;
Imaginary z1(2,3);
Imaginary z2(1,-1);
z1.print();
z2.print();
/*res = z1+z2;
cout<<"Addition:-\n";
res.print();
res = z1-z2;
cout<<"Subtraction:-\n";
res.print()*/
res = z1*z2;
cout<<"Multiplication:-\n";
res.print();
res = z1/z2;
cout<<"Division:-\n";
res.print();
return 0;
}
오류 메시지가 다음입니다 : 여기에 코드입니다 -
D:\Games\Cheese\main.cpp|66|error: no match for 'operator*' (operand types are 'Imaginary' and 'Imaginary')|
이 사람이 어떻게 수습하는 저를 보여주십시오.
구현시 문제가되는 것은 의도하지 않은 피연산자 'i'를 변경하는 것입니다. 2x 보완이기 때문에 다시 변경됩니다.그래서 매개 변수 나 객체 자체 (여기서는'operator ~'를 제외한 모든 연산자는 객체 자체를 변경 함)를 변경하지 않으려는 곳에'const :: '로 매개 변수를 표시하고 기능해야합니다. 연산자 x (const Imaginary & i) const'. – LeBlue