将对象指针的向量传递给类(c++)

Passing a vector of object pointers to a class (C++)

本文关键字:c++ 对象 指针 向量      更新时间:2023-10-16

我有一个对象指针向量

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;