c++ - 实现文件将只识别其他类的前向声明

标签 c++ include forward-declaration incomplete-type

我遇到一个问题,一个实现文件似乎只识别另一个类的前向声明,而不是它的实际声明。我试过对进口使用各种 guard 并取出前向声明但无济于事。

A 类有一个函数“decode”,它接受一个定义在单独文件中的 B 类型的参数。我想将所有 .h 和 .cpp 保留为不同的文件。他们在这里。

嗯:

class B;
class A{
private:
    string sentence;
public:
    A();
    void decode(const B& decoder);
};

B.h:

class B{
private:
    int code[26];
public:
    B();
    int getCode(int index);
};

A.cpp:

#include "A.h"
A::A(){}
double A::decode(const B& decoder){
    B.getCode(1);
    //other things
}

B.cpp:

#include "B.h"

B::B(){}
int B::getCode(int index){};

和司机:

#include "B.h"
#include "A.h"
using namespace std;
int main(int argc, char* argv[]){
    B myB;
    A myA;
    myA.decode(B);
}

我正在使用 g++ -Wall driver.cpp B.cpp A.cpp 编译它,但遇到了如下所示的错误:

A.cpp:4 错误:不完整类型“const class B”的无效使用

我浏览了大量类似的线程试图找到答案,但对我来说没有任何效果。有任何想法吗?

最佳答案

由于您在A.cpp 文件中使用了B 的成员函数getCode,因此仅前向声明是不够的,因为它没有提到B 的成员函数。整个 B 声明需要可用。为此,请在您的 A.cpp 文件中包含 "B.h" header :

#include "B.h"

正如评论中所指出的,您还应该利用 header guards A.hB.h header 。

关于c++ - 实现文件将只识别其他类的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630818/

相关文章:

c++ - 如何检测 VS C++ 编译器是否支持 C++11?

c++ - 身份验证 header 在 ONVIF 请求中不起作用?

css - 将其包含在 .jsp 页面中时发生冲突的 css 文件

c++ - 为什么我必须在 Microsoft Visual Studio C++ 应用程序中#include "stdafx.h"?

C++11 前向声明线程、互斥体、计时

javascript - Javascript 中不明确的函数声明

用于操作图像的 C++ 库

c++ - scanf(), std::cin 在多线程环境下如何表现?

android - 将值动态设置为包含 View 的 TextView

c++ - 使用extern时C++中的重新声明错误