2

我的 C++ 代码有问题。如果我插入#include "god.hpp",会neuron.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!";
}

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

亲切的问候-鲍里斯

编译:

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

1 回答 1

6

消除

#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文件)

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

于 2012-05-27T20:08:50.927 回答