类字段不能在函数内部访问

Class field not accessible inside of function

本文关键字:内部 访问 函数 字段 不能      更新时间:2023-10-16

当涉及到c++时,我相当愚蠢,因为我来自纯Java背景,具有良好的Python知识,但我试图用头文件中引用的矢量制作一个简单的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.
}

有趣的是,我可以访问像intstd::string这样的东西。当我尝试使用向量的时候,它就断了。什么好主意吗?

使用simulator::add_object,因为它是一个类方法,就像您已经为构造函数和析构函数所做的那样。

与Java相比,您可以在类定义之外定义函数(例如在额外的.cpp文件中,通常鼓励这样做),在这种情况下,您必须在函数签名前添加class_name::

如果不是,因为你的函数不在类命名空间中,它变成了一个非成员函数(意思是一个函数不属于任何类),它不知道objects成员是在你的simulator类。