C++中的转换构造函数

0 c++

下面的程序给出错误'无效使用不完整类型类Rectangle'和'类型矩形的前向声明'.如何解决这个问题而不编辑任何头文件?是否有任何可能的方法只使用构造函数进行转换?

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<<"\n\tANGLE: "<<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<<"\n\tY: "<<y;
    }

    friend Polar(Rectangle r);


};
Run Code Online (Sandbox Code Playgroud)

eml*_*lai 7

你试图访问不完整的类型Rectangle在你的Polar(Rectangle)构造函数.

由于Rectangle构造函数的定义也需要完整的定义Polar,因此您需要将类定义与构造函数定义分开.

解决方案:将您的成员函数的定义放在.cpp文件中,就像您应该这样做,如下所示:

polar.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
    ...
};
Run Code Online (Sandbox Code Playgroud)

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))
{
}
Run Code Online (Sandbox Code Playgroud)

以上初始化radiusangle括号内的内容.

rectangle.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
    ...
};
Run Code Online (Sandbox Code Playgroud)

rectangle.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))
{
}
Run Code Online (Sandbox Code Playgroud)

我还向您展示了如何使用构造函数初始化列表,您应该在C++中使用它来初始化成员变量.