I have made a application where you type the amount of books you want to enter and using overloaded operator ([]) but every time I give a pointer to store an array, it gives me an errors such as
2 IntelliSense: expression must have integral or unscoped enum type Line:11 Column:24 Library Books
and
Error 1 error C2440: 'initializing' : cannot convert from 'std::string' to 'unsigned int' Line:11 Column:1 Library Books
but anyway here is my code:
#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;
}
also I am not 100% sure if I have coded this correctly and if there are anymore errors please tell me and thanks.
This statement
storage = new string[book];
is invalid. The subscript value shall have integral or unscopped enueration type.
It seems your class definition has a typo and instead of
string book;
there should be for example
int book;
I think you meant the following
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]);
}
}
//...
And in main there should be
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();