c++ - c++定义前通过调用类初始化对应的类

标签 c++ class

我是第一次接触 C++,我试图找到我的问题,但我找不到好的答案。所以你能帮我吗? 所以我的问题是如何在定义之前使用类

我通过搜索和书籍学到了什么 1.我可以只声明类名并可以使用它 2. 我最好在未定义的类上使用指针

这段代码是在RectangularPoint和PolarPoint之间转换坐标系对应点 我在相应的 RP 上出错

class RectangularPoint; // predefine

class PolarPoint
{
public:
    double degree;
    double radialDistance;

public:
    PolarPoint():degree(0), radialDistance(0), correspondingRP_Defined(false), correspondingRP(new RectangularPoint()) {} // <--error
    PolarPoint(double _degree, double _radialDistance):
            degree(_degree),
            radialDistance(_radialDistance),
            correspondingRP_Defined(false),
            correspondingRP(new RectangularPoint()){} // <--error

public:
    void SetInfo(double _degree, double _radialDistance);
    RectangularPoint* toRectangular();

private:
    RectangularPoint *correspondingRP; // used pointer
    bool correspondingRP_Defined;
};


class RectangularPoint
{
public:
    double x;
    double y;

public:
    RectangularPoint(): x(0), y(0), correspondingRP_Defined(false), correspondingPP(new PolarPoint()) {}
    RectangularPoint(double x, double y): x(x), y(y), correspondingRP_Defined(false), correspondingPP(new PolarPoint()) {}

public:
    void SetInfo(double x, double y);
    PolarPoint* toPolar();

private:
    PolarPoint *correspondingPP;
    bool correspondingRP_Defined;
};

PolarPoint* RectangularPoint::toPolar() {
        if (correspondingRP_Defined) {
        return correspondingPP;
    } else {
        ...
        return correspondingPP;
    }
}

RectangularPoint* PolarPoint::toRectangular() {
    if (correspondingRP_Defined) {
        return correspondingRP;
    } else {
        ...
        return correspondingRP;
    }
}

我在相应的RP上出错

error: invalid use of incomplete type 'class RectangularPoint'

解决这个问题的好方法是什么?

最佳答案

你不能,所以你必须将该构造函数拆分成一个声明:

PolarPoint(double _degree, double _radialDistance);

和后来的定义(在类定义之外):

PolarPoint::PolarPoint(double _degree, double _radialDistance)
   : degree(_degree)
   , radialDistance(_radialDistance)
   , correspondingRP_Defined(false)
   , correspondingRP(new RectangularPoint())
{}

你的书也应该有一个例子(和解释)。

虽然这是一个相当普遍的问题,但如果您可以完全消除循环“引用”(通过重新处理您的设计),那就更好了。

关于c++ - c++定义前通过调用类初始化对应的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50117270/

相关文章:

c++ - 如何在 QTextDocument 中使用表格的框架属性,即使它不受支持?

java - 类测试期间出现 NullPointerException

ruby - 类(类型)检查

PHP 和 MySQL - 无法从查询中正确分配对象的字段值

c# - 什么是 C++ const 引用返回值的 c# 模拟

c++ - iMX31 依赖项?

c++ - 如何检测TCP连接中网线被拔掉?

c++ - 使用自定义源 boost Iostreams zlib_error

c++ - 如何制作一个实例化类并将它们排序在地址列表中的循环?

java - 通过二分查找查找数组中存储的信息