如何在另一个类中向vector添加类的对象。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class info{
private:
int id;
string name;
public:
info(int extId, string extName) {
this->id = extId;
this->name = extName;
}
};
class db {
private:
vector<info> infoVector;
public:
void pushData(info * data) {
this->infoVector.push_back(&data);
}
};
int main(){
info * testData = new info(123, "nice");
db database;
database.pushData(testData);
return 0;
}
我正在创建info
类的对象。该对象包含一个int
和一个string
变量。然后我创建了db
对象,我在那里传递了一个testData
对象。
我在构建项目时收到错误消息。
main.cpp: In member function ‘void db::pushData(info*)’:
main.cpp:23:44: error: no matching function for call to ‘std::vector<info>::push_back(info*&)’
this->infoVector.push_back(data);
^
In file included from /usr/include/c++/5/vector:64:0,
from main.cpp:2:
/usr/include/c++/5/bits/stl_vector.h:913:7: note: candidate: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = info; _Alloc = std::allocator<info>; std::vector<_Tp, _Alloc>::value_type = info]
push_back(const value_type& __x)
^
/usr/include/c++/5/bits/stl_vector.h:913:7: note: no known conversion for argument 1 from ‘info*’ to ‘const value_type& {aka const info&}’
我做错了什么?
答案 0 :(得分:1)
您似乎试图将info *
类型的地址传递给vector<info>::push_back
,only accepts types of const info &
or info &&
。致电push_back
时,请尝试使用dereference operator *
instead of the address-of operator &
:
this->infoVector.push_back(*data);
然而,这不是一种使用指针的好方法,如果从向量中删除data
或删除它,可能会导致内存泄漏或段错误。 vector
最好拥有其成员,因此您可以考虑改为:
class db {
private:
vector<info> infoVector;
public:
void pushData(info data) { // note: not a pointer
this->infoVector.push_back(data); // note: not address-of
}
};
int main(){
info testData(123, "nice"); // note: not a pointer
db database;
database.pushData(testData);
return 0;
}
否则,如果您真的希望infoVector
包含指针,请将其声明为:
std::vector<info*> infoVector;
然后删除address-to运算符。
答案 1 :(得分:-1)
您有vector<info>
,并且想要info *
,请尝试:
int main(){
info testData(123, "nice");
db database;
database.pushData(testData);
return 0;
}