在下面的代码中,我创建了一个基于书籍结构的对象,并且让它拥有多个"书籍",我设置的是一个数组(定义/启动的对象,即).但是,每当我去测试我的指针知识(练习帮助)并尝试制作一个指向创建对象的指针时,它就会给我错误:
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;
}
Run Code Online (Sandbox Code Playgroud)
*答案后的新代码(无错误)*
#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;
}
}
Run Code Online (Sandbox Code Playgroud)