我制作了一个应用程序,在其中输入要输入的书籍数量并使用重载运算符([]),但是每次我提供存储数组的指针时,都会出现如下错误:
2 IntelliSense:表达式必须具有整数或无作用域的枚举
类型行:11列:24图书馆书籍
和
错误1错误C2440:“正在初始化”:无法从
'std :: string'到'unsigned int'Line:11 Column:1 Library Books
但是无论如何这是我的代码:
#include <iostream>
#include <string>
using namespace std;
class Books{
private:
string* storage;
string book;
public:
Books(){
storage = new string[book];
}
void savebooks(int iterate){
for (int i = 0; i < iterate; ++i){
cout << "Book: ";
getline(cin, storage[i]);
}
}
const string operator[](const int ref){
return storage[ref];
}
~Books(){
delete storage;
}
};
int main(){
//local variables
int quantity;
//user display
cout << "Welcome to Book Storage Viewer" << endl;
cout << "How many books would you like to insert: ";
cin >> quantity;
//instantiante
Books bk;
//other handle
bk.savebooks(quantity);
//display books
cout << "These are the books you've entered" << endl;
for(int i = 0; i < quantity; ++i){
cout << bk[i] << endl;
}
system("pause");
return 0;
}
我也不是100%知道我是否正确编写了代码,如果还有错误,请告诉我,谢谢。
最佳答案
这个说法
storage = new string[book];
是无效的。下标值应具有整数或未限定范围的枚举类型。
看来您的课程定义有错字,而不是
string book;
应该有例如
int book;
我认为你的意思是
private:
string* storage;
int quantity;
public:
Books( int quantity) : quantity( quantity ) {
storage = new string[this->quantity];
}
void savebooks(){
for (int i = 0; i < quantity; ++i){
cout << "Book: ";
getline(cin, storage[i]);
}
}
//...
并且主要应该有
int quantity;
//user display
cout << "Welcome to Book Storage Viewer" << endl;
cout << "How many books would you like to insert: ";
cin >> quantity;
//instantiante
Books bk();
bk.savebooks();
关于c++ - C++重载运算符[],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22186907/