如何在对象的构造函数中添加(指针)到矢量

How to add (pointer of) an object to vector in its constructor?

本文关键字:指针 添加 对象 构造函数      更新时间:2023-10-16
#include <string>
#include <vector>
using namespace std;
struct object{
    int value;
    string name;
    object(string str, int val):name(str), value(val){
        objList.push_back(this);
    }
};
vector<object*> objList;

我想在创建对象时添加对象的指针,但程序给出错误:"使用未声明的标识符'objList'",我将 objList 的声明移到对象的定义上,它给出警告:"使用未声明的标识符'对象'"。创建对象时如何添加对象的指针?

尝试以下操作

using namespace std;
vector<struct object*> objList;
struct object{
    int value;
    string name;
    object(string str, int val): value(val), name(str) {
        objList.push_back(this);
    }
};

using namespace std;
struct object;
vector<object*> objList;
struct object{
    int value;
    string name;
    object(string str, int val): value(val), name(str) {
        objList.push_back(this);
    }
};