-1

I wanted to use casting operator to cast the Rect class to Polar class, But i am getting error stating "incomplete type". I am not getting any error on using pointers instead of the object itself. But I can't return a pointer to object for the purpose of casting.

#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;
  }

Is there a way I can use object of Polar class inside the Rect class. If not then how can pointers be used for the purpose of casting.

1 Answers1

3

No, you can't use anything that depends on the definition of Polar inside Rect. Polar hasn't been defined. Instead, change operator Polar() { ... } into a declaration: operator Polar(); and put its definition after Polar:

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

And, incidentally, this operator is a conversion operator. A cast is one way to ask for a conversion, but it's not the only way.

Oh, also, operator Polar() should be const, since it doesn't modify the object that it's applied to. So operator Polar() const; in the definition of Rect, and inline Rect::operator Polar() const { ... } for the definition.

Pete Becker
  • 69,019
  • 6
  • 64
  • 147