gpt4 book ai didi

c++ - 运算符重载类型转换 : Polar to cartesian c++

转载 作者:行者123 更新时间:2023-11-30 02:36:56 27 4
gpt4 key购买 nike

我需要将笛卡尔坐标转换为极坐标。我在转换为 polar 时遇到的错误是“Expected type specifier before Polar”。请帮帮我。我阅读了其他帖子,发现我需要指定类类型。我试过它指定为“笛卡尔”。我应该如何指定?提前谢谢。我在被注释掉的部分中收到错误

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
class Cartesian
{
double x,y;
public:
Cartesian()
{
x=0.0;y=0.0;
}
Cartesian(int x,int y)
{
this->x=x;
this->y=y;
}
Cartesian(const Cartesian& p)
{
x=p.x;
y=p.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
double operator-(Cartesian b)
{
double dist;
dist=sqrt((x-b.x)*(x-b.x)+(y-b.y)*(y-b.y));
return dist;
}
/*operator Polar()
{
Polar temp;
temp.r=sqrt((x*x)+(y*y));
temp.theta=atan(y/x);
return temp;
}*/




};


class Polar
{
double r,theta;
public:
Polar()
{
r=0.0;theta=0.0;
}
Polar(int r,int theta)
{
this->r=r;
this->theta=theta;
}
Polar(const Polar& p)
{
r=p.r;
theta=p.theta;

}
int getR()
{
return r;
}
int getTheta()
{
return theta;
}
double operator-(Polar b)
{
double dist;
dist=sqrt(r*r+(b.r)*(b.r)+2*(r)*(b.r)*cos(theta-b.theta));
return dist;

}

};

int operator==(Cartesian a,Cartesian b)
{
int t1,t2;
t1=a.getX();
t2=b.getX();
if(t1==t2)
{
t1=a.getY();
t2=b.getY();
if(t1==t2)
return 1;
}
return 0;
}

int operator==(Polar a,Polar b)
{
int t1,t2;
t1=a.getR();
t2=b.getR();
if(t1==t2)
{
t1=a.getTheta();
t2=b.getTheta();
if(t1==t2)
return 1;
}
return 0;
}

int operator==(Cartesian a,Polar b)
{

int t1,t2,t3,t4;
t1=a.getX();
t2=a.getY();
t3=b.getR();
t4=b.getTheta();
if((sqrt(t1*t1+t2*t2)==t3)&&(atan(t2/t1)==t4))
return 1;
else
return 0;
}






int main()
{
double temp1,temp2,temp3,temp4,distance;
cout<<"Enter the x and y coordinates of the first point\n";
cin>>temp1>>temp2;
Cartesian a1(temp1,temp2);
cout<<"Enter the x and y coordinates of the second point\n";
cin>>temp3>>temp4;
Cartesian b1(temp3,temp4);
distance=a1-b1;
cout<<distance<<"\n";
cout<<"Enter the r and theta coordinates of the first point\n";
cin>>temp1>>temp2;
Polar a2(temp1,temp2);
cout<<"Enter the r and theta coordinates of the second point\n";
cin>>temp3>>temp4;
Polar b2(temp3,temp4);
distance=a2-b2;
cout<<distance<<"\n";
if(a1==a2)
cout<<"True";





return 0;
}

最佳答案

在定义operator Polar的地方没有定义类Polar,所以需要在定义Polar之后前向声明并实现。此外,您正在访问 Polar 的私有(private)成员,因此您需要将 Cartesian 声明为 Polar 的友元:

class Polar; // forward declaration

class Cartesian {
//...

operator Polar(); // only the declaration
};

class Polar {
friend class Cartesian; // so that Cartesian sees private members

//...
};

// implementation of operator Polar()
Cartesian::operator Polar() {
Polar temp;
temp.r=sqrt((x*x)+(y*y));
temp.theta=atan(y/x);
return temp;
}

关于c++ - 运算符重载类型转换 : Polar to cartesian c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32212209/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com