c++ - C++ 中的转换构造函数

标签 c++

下面的程序给出错误“不完整类型类 Rectangle 的无效使用”和“类 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);


};

最佳答案

您正在尝试访问 Polar(Rectangle) 构造函数中的不完整类型 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
    ...
};

极地.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++ 中使用它来初始化成员变量。

关于c++ - C++ 中的转换构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29101199/

相关文章:

c++ - C程序检测物理链路状态和丢包

c++ - std::thread 和 std::endl 没有预期的输出

c++ - 是否可以使用 asio basic_stream_socket(或存在等效项)写入文件?

c++ - 在 C++ 中搜索树并输出到该节点的路径

c++ - 隐藏的依赖项的继承属性?

c++ - 在 g++ 编译中找不到 SDL.h

c++ - GL_UNSIGNED_INT_8_8_8_8_REV 在哪里定义?

C++ 数组指针 [] 或++

c++ - 使用 wm_paint 捕获游戏窗口

c++ - 如果我必须重写非虚拟成员函数怎么办