类字段不能在函数内部访问
Class field not accessible inside of function
当涉及到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.
}
有趣的是,我可以访问像int
或std::string
这样的东西。当我尝试使用向量的时候,它就断了。什么好主意吗?
使用simulator::add_object
,因为它是一个类方法,就像您已经为构造函数和析构函数所做的那样。
与Java相比,您可以在类定义之外定义函数(例如在额外的.cpp文件中,通常鼓励这样做),在这种情况下,您必须在函数签名前添加class_name::
。
如果不是,因为你的函数不在类命名空间中,它变成了一个非成员函数(意思是一个函数不属于任何类),它不知道objects
成员是在你的simulator
类。
相关文章:
- 如何从传递到对象的对象内部访问对象的类属性?
- 如何在类内部使用和访问静态指针到成员值s_ptm?
- 访问 Python 内部的C++文件
- C++ 如何访问内部枚举类?
- 访问说明符(私有/公共/受保护)如何在内部工作(限制成员访问)?
- 指针帮助:取消指向访问其内部数据的结构的指针
- C++:访问对象内部子对象的方法
- 访问lambda内部循环控制变量
- 如果访问对象,则指向的对象内部的指针会更改内存位置
- 如何通过从变量中获取类型来访问内部 typedef
- shared_ptr - 从包含的对象内部访问
- 从 OpenMP 循环内部访问和编辑 Qmap 时出错
- 我应该使用 "this" 关键字从成员函数内部访问类成员吗?
- 无法从指针数组或向量内部访问指向对象的成员
- 如何合理设计图书馆的外部访问而不干扰其内部访问
- 如何从对象内部访问变量
- 类字段不能在函数内部访问
- 在类的联合内部访问映射会产生分割错误
- 如何从类的一个成员类/结构内部访问类的成员数据
- 如何从另一个类内部访问一个类