将对象指针的向量传递给类(c++)
Passing a vector of object pointers to a class (C++)
我有一个对象指针向量
std::vector<myObject *> listofObjects;
我想把它们传递给另一个需要访问它们的对象
当我尝试做以下事情时:
class NeedsObjects
{
public:
NeedsObjects(std::vector<myObject *> &listofObjects)
private:
std::vector<myObject *> &listofObjects;
};
然后在初始化列表中初始化vector,得到以下错误:
'myObject' was not declared in this scope
template argument 1 is invalid
template argument 2 is invalid
我做错了什么?我所要做的就是将一个向量传递给NeedsObjects类。
您使用指向该对象的指针,因此您不必定义完整的对象结构,只需在使用它之前在此文件中声明它:
class myObject; // pre declaration, no need to know the size of the class
class NeedsObjects
{
public:
NeedsObjects(std::vector<myObject *> &listofObjects)
private:
std::vector<myObject *> &listofObjects;
};
您没有告诉编译器myObject
是什么,因此它不知道如何创建std::vector
。使用.h
文件添加引用或在此翻译单元中定义myObject
。
要么做
#include "myObject.h"
class NeedsObjects
{
public:
NeedsObjects(std::vector<myObject *> &listofObjects)
private:
std::vector<myObject *> &listofObjects;
};
如果您在单独的头中定义了myObject
或
class myObject {
//declaration goes here
};
class NeedsObjects
{
public:
NeedsObjects(std::vector<myObject *> &listofObjects)
private:
std::vector<myObject *> &listofObjects;
};
我看到你没有任何myOpbject类型的声明可见在你的代码
你基本上有两个选择:
a)包含完整声明myObject的头文件。
#include "myObject.h" // ... or something near to this.
b)假设myObject是一个类。你在这里提供的代码(至少声明部分)实际上不需要知道myObject的大小,所以你可以只声明myObject是一个类,它在其他地方声明。
class myObject;
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 使用"std::unordereded_map"映射到"std::list"对象