简体   繁体   中英

Vector error message and how to insert an object into a vector in C++?

I have a Room class and it has this constructor:

Room::Room(string a, int b, int c, string d)

And in my main function I do:

vector<Room> room;
sale.push_back("aaa", 1, 2, "ccc");

It gives me this error:

error: no matching function for call to ‘std::vector<Room, std::allocator<Room> >::push_back(const char [4])’

note: candidates are: void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Room, _Alloc = std::allocator<Room>]

I don't understand this error. How can I add a new room object into the vector?

Probably something like:

std::vector<Room> rooms;
room.push_back(Room("aaa", 1, 2, "ccc"));

You cannot use the push_back function as you do, just because the push_back function does not replaces the constructor. Here is the solution:

vector<Room> rooms;
Room ins("aaa",1,2,"ccc");
rooms.push_back(ins);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM