对于C++,我相当愚蠢,因为我来自具有良好Python知识的纯Java背景,但我正在尝试使用一个简单的C++类来引用头文件,并在源文件中的函数中访问它。我可以在构造函数中很好地访问它,但是只要我使用函数,根据Eclipse CDT和构建链,它显然不存在。无法在函数内部访问的类字段
头文件(simulator.h
):
#ifndef GAME_PHYSICS_SIMULATOR_H_
#define GAME_PHYSICS_SIMULATOR_H_
#include <vector>
#include "../world/object.h"
class simulator {
public:
simulator();
virtual ~simulator();
void add_object(object o);
private:
std::vector<object> objects;
};
#endif /* GAME_PHYSICS_SIMULATOR_H_ */
的源文件(simulator.cpp
):
#include "simulator.h"
simulator::simulator() {
object o;
objects.push_back(o); // Works fine in terms of acknowledging the existence of 'objects'.
}
simulator::~simulator() {}
void add_object(object o) {
objects.push_back(o); // Immediately throws error saying 'objects' doesn't exist.
}
有趣的是,虽然,是,我可以访问诸如int
的或std::string
的事情精细。只要我尝试使用矢量,就会中断。有任何想法吗?
为什么downvote? – finnrayment
目前您将'add_object'定义为全局非成员函数。 –
Downvote我不知道,但无论如何都投票结束,因为它可能对未来的访问者没有用处,并且标题使得很难发现。 joachim的意思是:如果没有'simulator ::',编译器会将它视为全局命名空间 – stijn