G++ 错误:在包含的文件中,未声明 Foo

G++ Error: In file included, then Foo was not declared

本文关键字:未声明 Foo 文件 错误 包含 G++      更新时间:2023-10-16

我的C++代码有问题。如果我在neuron.hpp中插入#include "god.hpp"g++显示以下错误:

In file included from neuron.hpp:4,
             from main.cpp:5:
god.hpp:11: error: ‘Neuron’ has not been declared
god.hpp:13: error: ‘Neuron’ was not declared in this scope
god.hpp:13: error: template argument 1 is invalid
god.hpp:13: error: template argument 2 is invalid
main.cpp: In function ‘int main()’:
main.cpp:36: error: no matching function for call to ‘God::regNeuron(Neuron*&)’
god.hpp:11: note: candidates are: long int God::regNeuron(int*)
In file included from god.hpp:5,
             from god.cpp:3:
neuron.hpp:10: error: ‘God’ has not been declared
In file included from neuron.hpp:4,
             from neuron.cpp:2:
god.hpp:11: error: ‘Neuron’ has not been declared
god.hpp:13: error: ‘Neuron’ was not declared in this scope
god.hpp:13: error: template argument 1 is invalid
god.hpp:13: error: template argument 2 is invalid

以下是必要文件的相关(部分):

//main.cpp
#include <string>
#include <vector>
#include "functions.hpp"
#include "neuron.hpp"
#include "god.hpp"
using namespace std;
int main()
{
God * god = new God();
vector<string>::iterator it;
for(it = patterns.begin(); it != patterns.end(); ++it) {
    Neuron * n = new Neuron();
            god->regNeuron(n);
    delete n;
    cout << *it << "n";
}
}

上帝;)谁将处理所有神经元...

//god.hpp
#ifndef GOD_HPP
#define GOD_HPP 1 
#include <vector>
#include "neuron.hpp"
class God
{
public:
    God();
    long regNeuron(Neuron * n);
private:
    std::vector<Neuron*> neurons;
};
#endif
//god.cpp
#include <iostream>
#include <vector>
#include "god.hpp"
#include "neuron.hpp"
using namespace std;

God::God()
{
vector<Neuron*> neurons;
}
long God::regNeuron(Neuron * n)
{
neurons.push_back(n);
cout << neurons.size() << "n";
return neurons.size();
}

至少,我的神经元。

//neuron.hpp
#ifndef NEURON_HPP
#define NEURON_HPP 1
#include "god.hpp" //Evil
class Neuron
{
public:
    Neuron();
    void setGod(God *g);
};
#endif
//neuron.cpp
#include <iostream>
#include "neuron.hpp"
#include "god.hpp"
Neuron::Neuron()
{
}
void Neuron::setGod(God *g)
{
std::cout << "Created Neuron!";
}

我希望有人可以帮助我找到错误。当我用neuron.hpp#include "god.hpp"时,就会发生这种情况。我用谷歌搜索了大约三个小时,但我没有运气。

亲切问候-鲍里斯

编译方式:

g++ -Wall -o getneurons main.cpp functions.cpp god.cpp neuron.cpp

删除

#include "god.hpp" 

并将其替换为前向声明:

//neuron.hpp
#ifndef NEURON_HPP
#define NEURON_HPP 1
class God;  //forward declaration
class Neuron
{
public:
    Neuron();
    void setGod(God *g);
};
#endif

God.hpp相同:

//god.hpp
#ifndef GOD_HPP
#define GOD_HPP 1 
#include <vector>
class Neuron; //forward declaration
class God
{
public:
    God();
    long regNeuron(Neuron * n);
private:
    std::vector<Neuron*> neurons;
};
#endif

请注意,您需要在实现文件中包含。( cpp文件 )

如果使用指针或对对象的引用作为成员,或者将该类型用作返回类型或参数,则不需要完整定义,因此前向声明就足够了。