实现文件只会识别其他类的前向声明

时间:2018-02-05 20:19:23

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

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

A类有一个功能" decode"它接受一个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 class B'

我已经看了很多类似的线索试图找到答案,但是对我来说什么都没有用。有任何想法吗?

2 个答案:

答案 0 :(得分:2)

由于您在B文件中使用了getCode的成员函数A.cpp,因此前向声明仅仅不足以说明B成员的任何内容功能。需要提供整个B声明。为此,请在"B.h"文件中添加A.cpp标题:

#include "B.h"

正如评论中所指出的,您还应该使用A.hB.h标题{/ 3}}。

答案 1 :(得分:0)

最佳做法是每个.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);
}