错误:返回类型 'class Polar' 不完整,无效使用类型 'polar'

Error: return type 'class Polar' is incomplete, invalid use of type 'polar'

本文关键字:无效 polar 类型 返回类型 class Polar 错误      更新时间:2023-10-16

我想使用转换运算符将 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 类的对象。如果那么指针如何用于铸造目的。

不,您不能使用任何依赖于Rect内部Polar定义的内容。 Polar尚未定义。相反,将operator Polar() { ... }更改为声明operator Polar();并将其定义放在Polar之后:

inline Rect::operator Polar() {
    return Polar(sqrt(x*x + y*y) , atan(y/x)*(180/3.141));
}

顺便说一下,这个运算符是一个转换运算符。演员阵容是要求转换的一种方式,但不是唯一的方法。

哦,还有,operator Polar()应该是const的,因为它不会修改它所应用到的对象。所以operator Polar() const;Rect的定义中,inline Rect::operator Polar() const { ... }定义。