首页 > 解决方案 > 前向定义类的类型转换重载

问题描述

我有一个将笛卡尔坐标转换为极坐标的简单程序。我也想反之亦然。因此,我尝试通过前向声明将类型转换运算符与笛卡尔类一起使用。

#include<iostream>
#include<math.h>
using namespace std;

class Cartesian;

class Polar{
   double dist,angle;
   public:
   Polar(double a,double b): dist(a),angle(b){}
   Polar(){ dist=0; angle=0; }  //In case no parameters provided, this default constructor will be called
   operator Cartesian(){
      double x=dist*cos((angle/180)*M_PI);
      double y=dist*sin((angle/180)*M_PI);
      return Cartesian(x,y);
   }
   friend double getDATA(Polar,int);
};

double getDATA(Polar a,int opt=1){
   if(opt==1) return a.dist;
   else return a.angle;
}

class Cartesian{
   double x,y;
   public: Cartesian(){ x=0; y=0; }
   Cartesian(double a,double b): x(a),y(b){}
   operator Polar(){   //NOTICE:- No return type is mentioned
     double distance= sqrt(x*x+y*y);
     double angle= atan(y/x);
     angle=(angle*180)/M_PI;
     return Polar(distance,angle);  //Note that new keyword is used to return pointers (allocate memory in the heap), don't use it here
   }
};

int main(){
  double x,y;
  cout<<"Enter the X and Y coordinates= "; cin>>x>>y;
  Cartesian c(x,y);
  Polar p=c;
  cout<<"Distance= "<<getDATA(p)<<endl;
  cout<<"Gradient= "<<getDATA(p,3)<<endl;
  return 0;
}

但是在编译时,它给了我这两个错误:

  1. 返回类型“类笛卡尔”不完整
  2. 不完整类型“笛卡尔类”的无效使用

有解决方法吗?我真的希望这两个类能够相互转换。

标签: c++oopc++11c++17c++14

解决方案


C++ 中不支持类的前向声明吗?

是的,C++ 支持类的前向声明。

但是,您不能定义返回类型不完整的函数。您必须在定义函数之前定义返回类型。

现在我明白了。但是有没有解决方法

是的。在定义函数之前定义返回类型。


推荐阅读