다른 클래스의 벡터에 클래스의 객체를 추가하는 방법.벡터를 사용하는 클래스 객체를 push_back합니다.
#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&}’
내가 뭘 잘못하고 있니?
그것은 "에 ... CONST 정보 및 '정보 *'에서 인수 1 알려진 변환"오류 메시지에 있습니다. 'vector infoVector;를 가지고 있는데'info' 타입을 받아들이지 만'info *'타입을 주려고합니다. –
왜 새로 사용하십니까? –
제임스가 지적한 것보다 약간 나쁩니다. 'pushData'는 포인터를 취하고 포인터의 주소는 함수의 임시 포인터이며'push_back'으로 전달됩니다. 이것은 주어진 오류 메시지와 일치하지 않으므로 디버깅하는 동안 약간의 실연의 결과라고 생각합니다. 유용한 참고 사항 : [참고 vs. 포인터 사용시기] (https://stackoverflow.com/questions/7058339/when-to-use-references-vs-pointers) – user4581301