c++ - 前向定义类的类型转换重载
问题描述
我有一个将笛卡尔坐标转换为极坐标的简单程序。我也想反之亦然。因此,我尝试通过前向声明将类型转换运算符与笛卡尔类一起使用。
#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;
}
但是在编译时,它给了我这两个错误:
- 返回类型“类笛卡尔”不完整
- 不完整类型“笛卡尔类”的无效使用
有解决方法吗?我真的希望这两个类能够相互转换。
解决方案
C++ 中不支持类的前向声明吗?
是的,C++ 支持类的前向声明。
但是,您不能定义返回类型不完整的函数。您必须在定义函数之前定义返回类型。
现在我明白了。但是有没有解决方法
是的。在定义函数之前定义返回类型。
推荐阅读
- c# - 具有字符串名称的枚举数组
- wso2 - 如何在服务器上部署 api 管理器?
- javascript - 修改这个漂亮的数字自动收报机
- angular - 如何以角度获取输入类型=月份的值
- scrollview - 如何在 SwiftUI 中禁用 ScrollView 弹跳
- r - 根据名称有条件地乘以值
- javascript - 单击下一张图像时渲染下一张图像?
- javascript - 如何在数组中存储多个经纬度并在航路点中访问它们以在它们之间创建路线?
- php - SilverStripe 3.7:如何在没有空格的情况下呈现模板语法或 PHP 输出?
- python - 设备类型为 cuda 的预期对象,但在 Pytorch 中获得了设备类型 cpu