有类似的问题,但它们都是 C 语言,而不是 C++,所以我问了一个新问题。
我一直在学习C++ 教程,在完成动态内存、指针和结构部分之后,我尝试将它们放在一个示例程序中。
本质上,我试图拥有一个动态分配的结构数组(程序输入“produce”:P 并显示结果)。
编译器错误:'base operand of '->' has non-pointer type 'produce'
对于代码fruit[i]->item;
抱歉,如果代码有点冗长(我不想省略部分以防它们是问题,即使这会导致问题“过于本地化”):
#include <iostream>
#include <string>
#include <new>
using namespace std;
struct produce {
int price;
string item;
};
int main(void) {
int num;
int i;
//Get int for size of array
cout << "Enter the number of fruit to input: ";
cin >> num;
cout << endl;
//Create a dynamically allocated array (size num) from the produce structure
produce *fruit = new (nothrow) produce[num];
if (fruit == 0) {
cout << "Error assigning memory.";
}
else {
//For 'num', input items
for (i = 0; i < num; i++) {
cout << "Enter produce name: ";
//Compiler error: 'base operand of '->' has non-pointer type 'produce'
cin >> fruit[i]->item;
cout << endl;
cout << "Enter produce price: ";
cin >> fruit[i]->price;
cout << endl;
cout << endl;
}
//Display result
for (i = 0; i < num; i++) {
cout << "Item: " << fruit[i]->item << endl;
cout << "Cost: " << fruit[i]->price << endl;
cout << endl;
}
//Delete fruit to free memory
delete[] fruit;
}
return 0;
}