【发布时间】:2019-02-11 16:25:09
【问题描述】:
我想使用转换运算符将 Rect 类转换为 Polar 类, 但我收到错误说明“类型不完整”。我没有得到任何 使用指针而不是对象本身时出错。但我不能回来 一个指向对象的指针,用于强制转换。
#include<iostream>
#include<cmath>
using namespace std;
class Polar;
class Rect{
double x;
double y;
public:
Rect(double xx, double yy): x(xx), y(yy) {}
void display(void){
cout<<x<<endl;
cout<<y<<endl;
}
operator Polar(){//need help regarding this function
return Polar(sqrt(x*x + y*y) , atan(y/x)*(180/3.141));
}
};
class Polar{
double r;
double a;
double x;
double y;
public:
Polar(double rr, double aa){
r=rr;
a=aa*(3.141/180);
x= r* cos(a);
y= r* sin(a);
}
Polar(){
r=0;
a=0;
x=0;
y=0;
}
Polar operator+(Polar right){
Polar temp;
//addition
temp.x= x+ right.x;
temp.y= x+ right.y;
//conversion
temp.r= sqrt(temp.x*temp.x + temp.y*temp.y);
temp.a= atan(temp.y/temp.x)*(180/3.141);
return temp;
}
operator Rect(){
return Rect(x,y);
}
friend ostream & operator <<(ostream &out, Polar a);
double getr(){
return r;
}
double geta(){
return a;
}
};
ostream & operator <<(ostream &out,Polar a){
out<<a.getr()<<", "<<a.geta()<<endl;
return out;
}
int main()
{
Polar a(10.0, 45.0);
Polar b(8.0, 45.0);
Polar result;
//+ operator overloading
result= a+b;
//<< overloading
cout<<result<<endl;
Rect r(18,45);
Polar p(0.2,53);
r=p;//polar to rect conversion
r.display();
return 0;
}
有没有办法可以在 Rect 类中使用 Polar 类的对象。如果 不是那么如何将指针用于强制转换。
【问题讨论】:
标签: c++ incomplete-type