C++中的转换构造函数
Conversion Constructor in C++
下面的程序给出错误"不完整类型类Rectangle的无效使用"answers"类Rectanger的正向声明"。如何在不编辑任何头文件的情况下修复此问题?难道没有任何可能的方法只使用构造函数来进行转换吗?
include<iostream>
include<math.h>
using namespace std;
class Rectangle;
class Polar
{
int radius, angle;
public:
Polar()
{
radius = 0;
angle = 0;
}
Polar(Rectangle r)
{
radius = sqrt((r.x*r.x) + (r.y*r.y));
angle = atan(r.y/r.x);
}
void getData()
{
cout<<"ENTER RADIUS: ";
cin>>radius;
cout<<"ENTER ANGLE (in Radians): ";
cin>>angle;
angle = angle * (180/3.1415926);
}
void showData()
{
cout<<"CONVERTED DATA:"<<endl;
cout<<"tRADIUS: "<<radius<<"ntANGLE: "<<angle;
}
friend Rectangle :: Rectangle(Polar P);
};
class Rectangle
{
int x, y;
public:
Rectangle()
{
x = 0;
y = 0;
}
Rectangle(Polar p)
{
x = (p.radius) * cos(p.angle);
y = (p.radius) * sin(p.angle);
}
void getData()
{
cout<<"ENTER X: ";
cin>>x;
cout<<"ENTER Y: ";
cin>>y;
}
void showData()
{
cout<<"CONVERTED DATA:"<<endl;
cout<<"tX: "<<x<<"ntY: "<<y;
}
friend Polar(Rectangle r);
};
您正试图访问Polar(Rectangle)
构造函数中的不完整类型Rectangle
。
由于Rectangle
构造函数的定义也需要Polar
的完整定义,因此需要将类定义与构造函数定义分离。
解决方案:将成员函数的定义放在.cpp文件中,正如您应该做的那样,如下所示:
极性。h:
class Rectangle; // forward declaration to be able to reference Rectangle
class Polar
{
int radius, angle;
public:
Polar() : radius(0), angle(0) {} // initializes both members to 0
Polar(Rectangle r); // don't define this here
...
};
polar.cpp:
#include "polar.h"
#include "rectangle.h" // to be able to use Rectangle r
Polar::Polar(Rectangle r) // define Polar(Rectangle)
: radius(sqrt((r.x*r.x) + (r.y*r.y))),
angle(atan(r.y/r.x))
{
}
上面将radius
和angle
初始化为括号内的内容。
矩形.h:
class Polar; // forward declaration to be able to reference Polar
class Rectangle
{
int x, y;
public:
Rectangle() : x(0), y(0) {} // initializes both x and y to 0
Rectangle(Polar p); // don't define this here
...
};
矩形.cpp:
#include "rectangle.h"
#include "polar.h" // to be able to use Polar p
Rectangle::Rectangle(Polar p) // define Rectangle(Polar)
: x((p.radius) * cos(p.angle)),
y((p.radius) * sin(p.angle))
{
}
我还向您展示了如何使用构造函数初始化列表,您应该在C++中使用该列表来初始化成员变量。
如何在不编辑任何头文件的情况下修复此问题。
你不能。Polar(Rectangle)
的定义必须在Rectangle
的定义之后,因此Rectangle
在构造函数需要使用它的地方是完整的
只需在类定义中声明构造函数:
Polar(Rectangle r);
并在其他地方对其进行定义;在源文件中,或者在定义Rectangle
之后的头中(在这种情况下,您需要将其标记为inline
)。
就我个人而言,我会把它分成两个头,每个类一个,并在源文件中定义所有成员(除非我已经证明出于性能原因,它们需要内联)。然后,每个头只需要声明另一个类,并且只需要从实现或使用这些类的源文件中包含。
相关文章:
- 构造函数和转换运算符之间的重载解析
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- enable_if转换构造函数(静态强制转换,is_base_of)
- 参数包构造函数在类模板中隐藏用户定义的转换
- c++ 构造函数 将 1 个字符串参数转换为 3 个属性
- 复制构造函数隐式转换问题
- 没有合适的构造函数可以从"float"转换为"_D3DCOLORVALUE"
- 如果存在从"双精度"到"T"的转换,则禁用构造函数
- C++隐式构造函数转换,后跟类型向上转换
- 此语法中的构造函数转换错误
- C 操作员在具有构造函数转换时过载
- 如何在允许拷贝限制的同时禁用隐式构造函数转换
- 构造函数转换
- 通过构造函数转换容器
- C++ "没有合适的构造函数可以从<默认构造函数>转换为参数化构造函数
- 多个隐式构造函数转换
- (涉及显式)运算符和构造函数转换的优先级
- 构造函数转换如何在C++中工作
- 如何修复GCC编译中的const char *构造函数转换链错误
- 隐式构造函数转换的编译器优化