【问题标题】:Error: return type 'class Polar' is incomplete, invalid use of type 'polar'错误:返回类型 'class Polar' 不完整,无效使用类型 'polar'
【发布时间】: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


    【解决方案1】:

    不,您不能使用任何取决于Polar inside Rect 定义的东西。 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 { ... }在定义中。

    【讨论】:

    • ...并修复该转换器从弧度到度数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多