我想创建一个指针 vector ,每个指针都指向它们自己的火星对象,但我不知道如何安排它。我目前收到错误
Non-const lvalue reference to type 'vector' cannot bind to a value of unrelated type 'martianDatabase'
但是错误会随着我所做的每一次更改而不断变化。过去两天我看了很多教程,试图弄清楚这个问题,但我仍然卡住了。
struct Martian
{
Martian(string fname, string lname, string ssid);
string fname, lname, ssid;
~Martian();
};
class martianDatabase
{
vector<Martian*> database;
martianDatabase();
void addMartian(vector <Martian*> &database, int &iterator, string f, string l, string id);
int iterator = 0;
};
Martian::Martian(string f, string l, string id)
{
fname = f;
lname = l;
ssid = id;
}
void martianDatabase::addMartian(vector <Martian*> &database, int &i, string f, string l, string id)
{
Martian* m = new Martian(f, l, id);
database[i].push_back(m);
i++;
}
最佳答案
您的代码有几处错误:
- 你不应该通过你的
vector<Martian*>
作为addMartian
的参数,相反,您可以通过this
访问它指针。 - 不需要你的
int& iterator
,因为您要做的就是添加您的Martian
到 vector 的末尾 - 您的代码
database[i].push_back(m);
获取 vector 的第 i 个元素database
,这是一个Martian&
, 然后尝试调用push_back(m)
在它上面,这是不可能的,因为没有为Martian
类型声明这样的函数。 ,你可能想要的是database.push_back(m)
, 其中插入m
在database
的后面 vector
考虑以下替代方案:
class martianDatabase
{
vector<Martian*> database;
martianDatabase();
void addMartian(string f, string l, string id);
};
void martianDatabase::addMartian(string f, string l, string id)
{
this->database.push_back(new Martian(f, l, id));
}
虽然这不是真正的问题,但在您的构造函数中直接初始化成员(如果可能)可能会更好,而不是复制分配它们,即使用代码:
Martian::Martian(string f, string l, string id) : fname(f), lname(l), ssid(id) { }
关于c++ - 我如何制作指向动态分配对象的指针 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36962090/