我遇到了一个问题,即实现文件仅识别另一个类的正向声明,而不是其实际声明。我已经尝试使用各种导入的警卫并取出前瞻性声明,但无济于事。
类A类具有一个函数"解码",该函数需要一个在单独文件中定义的类型B的参数。我想将所有.h和.cpp保留为不同的文件。他们在这里。
A.H:
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 b'
无效我浏览了许多类似的线程,试图找到答案,但是还没有对我有用。有任何想法吗?
由于您在A.cpp
文件中使用了B
的成员函数getCode
,因此向前声明仅仅是不够的,因为它对B
的成员函数一无所知。整个B
声明都需要可用。为此,在您的A.cpp
文件中包括"B.h"
标头:
#include "B.h"
如评论中指出的那样,您还应该使用A.h
和B.h
标头的标头护罩。
最佳实践是每个.h文件都包含所需的一切。这意味着A.H应包括B.H。
A.H:
#pragma once // Or equivalent include-guard macros
#include "B.h"
class A{
private:
string sentence;
public:
A();
void decode(const B& decoder);
};
b.h:
#ifndef B_h
#define B_h true
class B{
private:
int code[26];
public:
B();
int getCode(int index);
};
#endif
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 "A.h"
void main(){
B myB;
A myA;
myA.decode(B);
}