我遇到一个问题,一个实现文件似乎只识别另一个类的前向声明,而不是它的实际声明。我试过对进口使用各种 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.h
和 B.h
header 。
关于c++ - 实现文件将只识别其他类的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630818/