簡體   English   中英

C ++中的轉換構造函數

[英]Conversion Constructor in 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
    ...
};

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初始化radius方括號內的內容。

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

就個人而言,我會通過將其拆分為兩個標頭(每個類一個)並定義源文件中的所有成員(除非出於性能原因已證明它們必須是內聯的)的方式進行整理。 然后,每個標頭僅需要聲明另一個類,並且僅需要從實現或使用這些類的源文件中包含這些標頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM