引用不完整的类类型 - C++

Lap*_*pys 1 c++

想象一下这个假设情景.

我创建了两个类Boolean,String它们彼此独立(包括它们各自的方法和属性).

我需要一个这样的类(Boolean)来创建一个新的,String当它中的某个方法被调用(让我们说toString)时,另一个(String)BooleanisEmpty调用it()中的方法时创建一个新的.

这是代码:

消息代码1

#include <string.h>

class Boolean;
class String;

class Boolean {
    bool value = false;
    public:
        Boolean(bool value) { this -> value = value; }
        String toString() { return String(value ? "true" : "false"); }
};

class String {
    char* value;
    public:
        String(const char* value) { this -> value = strdup(value); }
        Boolean isEmpty() { return Boolean(!strcmp(value, "")); }
};
Run Code Online (Sandbox Code Playgroud)

当然,这不起作用,因为在Boolean类' toString方法中,编译器抱怨String它用于构造新对象的类是不完整的类型.

到目前为止我能够得到的最远的是下面的代码(我知道这是准确的):

消息代码2

class Boolean;
class String;

class Boolean {
    bool value = false;
    public:
        String* toString() {
            String* string;
            return string;
        }
};

class String {
    char* value;
    public:
        Boolean* isEmpty() {
            Boolean* boolean;
            return boolean;
        }
};
Run Code Online (Sandbox Code Playgroud)

但是,当然,如果我从已编译的C++文件中运行此代码,它将使用打印Boolean对象的字符串值Boolean.toString,它将返回任意且不准确的内容.

第一个源代码脚本中的概念如何转换为正常运行的C++代码?

感谢您阅读(并帮助).

sco*_*001 8

你很接近,但是当你正在进行类实现时Boolean,它唯一知道的是会String在某个时候命名一个类.它对String构造函数一无所知,所以你还不能打电话给它们!

相反,你可以声明类名,实现类,而只有宣布他们的功能,然后实际实现的功能后,这两个类和它们的功能得到了充分的声明.

这看起来像:

class String; //We need to know there will be a class String for Boolean declaration

class Boolean {
    bool value = false;
    public:
        Boolean(bool value) { this -> value = value; }
        //We can't implement this yet since it requires 
        // calling String functions which haven't been declared yet
        String toString(); 
};

class String {
    char* value;
    public:
        String(const char* value) { this -> value = strdup(value); }
        //This is fine to implement since Boolean is already fully declared
        Boolean isEmpty() { return Boolean(!strcmp(value, "")); }
};

//String has been declared, now we can implement this function
String Boolean::toString() { return String(value ? "true" : "false"); }
Run Code Online (Sandbox Code Playgroud)

看到它在这里工作:ideone


你的指针示例工作的原因是因为指针没有调用任何构造函数.制作指针时唯一需要知道的是一个类存在.如果您尝试使用该new运算符,您可能会遇到同样的问题,因为此时您无法知道String该类将具有哪些构造函数.