C++中的转换构造函数

Conversion Constructor in C++

本文关键字:构造函数 转换 C++      更新时间:2023-10-16

下面的程序给出错误"不完整类型类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))
{
}

上面将radiusangle初始化为括号内的内容。

矩形.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)。

就我个人而言,我会把它分成两个头,每个类一个,并在源文件中定义所有成员(除非我已经证明出于性能原因,它们需要内联)。然后,每个头只需要声明另一个类,并且只需要从实现或使用这些类的源文件中包含。