c++ - Problem populating dynamically created array -
in code below, trying use for
loop initialise member name
of 5 objects of class book
using names taken string array array
(numbers in case testing purposes).
#include <iostream> #include <string> using namespace std; class book { private: string name; public: book(); book(string&); }; book :: book() {} book :: book(string& temp) { name = temp; } int main() { string array[] = {"1", "2", "3", "4", "5"}; book *booklist = new book[5]; (int count = 0; count < 5; count ++) { booklist[count] = new book(array[count]); } return 0; }
however, whenever try compile code, following error:
main.cpp: in function ‘int main()’: main.cpp:28: error: no match ‘operator=’ in ‘*(booklist + ((unsigned int)(((unsigned int)count) * 4u))) = (operator new(4u), (<statement>, ((book*)<anonymous>)))’ main.cpp:6: note: candidates are: book& book::operator=(const book&)
my intention create array of objects using private member values known once loop collects relevant data. i'm following advice offered in answer #2 question asked here previously.
book *booklist = new book[5];
booklist
array of 5 book
objects.
booklist[count] = new book(array[count]);
you trying use booklist
if array of 5 pointers book
objects.
booklist[count]
not pointer count
th book
, is count
th book
.
have considered using 1 of standard library containers, std::vector
?
std::vector<book> booklist(5);
or, if don't want insert book
s until know are, can create initial size of 0
(by removing (5)
initializer) , push_back
or insert
books need to.
Comments
Post a Comment