以下のコードでは、本の構造に基づいてオブジェクトを作成し、複数の「本」を保持するために、配列(つまり、定義/開始されるオブジェクト)を設定します。ただし、ポインターの知識をテストし(練習が役立ちます)、作成されたオブジェクトを指すポインターを作成しようとすると、エラーが発生します。
C:\ Users \ Justin \ Desktop \ Project \ wassuip \ main.cpp | 18 |エラー:「本」から「本」への割り当てに互換性のないタイプ* [4]'| *
これは、オブジェクトbook_arr []が配列であるため、すでにポインターと見なされているためですか?ありがとう(C ++は初めてで、確認したいだけです)。
#include <iostream>
#include <vector>
#include <sstream>
#define NUM 4
using namespace std;
struct books {
float price;
string name;
int rating;
} book_arr[NUM];
int main()
{
books *ptr[NUM];
ptr = &book_arr[NUM];
string str;
for(int i = 0; i < NUM; i++){
cout << "Enter book name: " << endl;
cin >> ptr[i]->name;
cout << "Enter book price: " << endl;
cin >> str;
stringstream(str) << ptr[i]->price;
cout << "Enter book rating: " << endl;
cin >> str;
stringstream(str) << ptr[i]->rating;
}
return 0;
}
*回答後の新しいコード(エラーなし)*
#include <iostream>
#include <vector>
#include <sstream>
#define NUM 4
using namespace std;
/* structures */
struct books {
float price;
string name;
int rating;
} book[NUM];
/* prototypes */
void printbooks(books book[NUM]);
int main()
{
string str;
books *ptr = book;
for(int i = 0; i < NUM; i++){
cout << "Enter book name: " << endl;
cin >> ptr[i].name;
cout << "Enter book price: " << endl;
cin >> str;
stringstream(str) << ptr[i].price;
cout << "Enter book rating: " << endl;
cin >> str;
stringstream(str) << ptr[i].rating;
}
return 0;
}
void printbooks(books book[NUM]){
for(int i = 0; i < NUM; i++){
cout << "Title: \t" << book[i].name << endl;
cout << "Price: \t$" << book[i].price << endl;
cout << "Racing: \t" << book[i].rating << endl;
}
}