这是我的代码:

#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语言中可以正常工作...

怎么了?

最佳答案

完成的操作被声明为applebananamelon作为product的全局实例,而main函数表明您想将它们声明为类型。为此,您可以在声明中使用typedef关键字。 (尽管为什么您需要struct product这么多同义词?)

这和C没什么不同。在您的示例中C和C++之间的唯一区别是,在C++中product命名一个类型,而在C中您必须指定struct product。 (除了更明显的事实,即C中不能包含#include <iostream>using namespace std;。)

例如,声明applebananamelon作为struct product的同义词:

typedef struct product {
  int weight;
  float price;
} apple, banana, melon;

09-10 00:16
查看更多