这是我的代码:
#include <iostream>
using namespace std;
struct product {
int weight;
float price;
} apple, banana, melon; // can I declare like this ?????
int main()
{
apple a;
}
当我编译此样本时,编译器会说:
struct.cpp|11|error: expected ';' before 'a'|
相同的东西在C语言中可以正常工作...
怎么了?
最佳答案
完成的操作被声明为apple
,banana
和melon
作为product
的全局实例,而main
函数表明您想将它们声明为类型。为此,您可以在声明中使用typedef
关键字。 (尽管为什么您需要struct product
这么多同义词?)
这和C没什么不同。在您的示例中C和C++之间的唯一区别是,在C++中product
命名一个类型,而在C中您必须指定struct product
。 (除了更明显的事实,即C中不能包含#include <iostream>
或using namespace std;
。)
例如,声明apple
,banana
和melon
作为struct product
的同义词:
typedef struct product {
int weight;
float price;
} apple, banana, melon;