在下面的代码中,我基于书籍结构创建了一个对象,并让它保存多个我设置的“书籍”是一个数组(即定义/启动的对象)。但是,每当我去测试我的指针知识(实践有帮助)并尝试创建一个指向创建对象的指针时,它都会给我一个错误:
C:\Users\Justin\Desktop\Project\wassuip\main.cpp|18|错误:“books ”分配给“books* [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;
}
}