在下面的代码中,我尝试使用for循环来初始化Name类的五个对象的成员,book使用从字符串数组中取出的名称Array(在这种情况下为了测试目的而使用数字).
#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];
for (int count = 0; count < 5; count ++)
{
BookList[count] = new book(Array[count]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,每当我尝试编译代码时,我都会收到以下错误:
main.cpp: In function ‘int main()’:
main.cpp:28: error: no match for ‘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&)
Run Code Online (Sandbox Code Playgroud)
我的目的是使用私有成员值创建一个对象数组,只有在循环收集相关数据时才会知道.我正在按照我在此前问过的问题回答#2中提出的建议.
book *BookList = new book[5];
Run Code Online (Sandbox Code Playgroud)
BookList是一个包含五个book对象的数组.
BookList[count] = new book(Array[count]);
Run Code Online (Sandbox Code Playgroud)
您正在尝试使用BookList,就好像它是一个包含五个指向book对象的数组.
BookList[count]不是指针到count第book,它是该count次book.
您是否考虑过使用其中一个标准库容器std::vector?
std::vector<book> BookList(5);
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想在book知道它们之前插入s,则可以根据需要创建初始大小0(通过删除(5)初始化程序)和/ push_back或insert书籍.