C++结构声明和用法编译器错误

Dav*_*ani 1 c++ struct

这是我的代码:

#include <iostream>
using namespace std;

struct product {
  int weight;
  float price;
} apple, banana, melon; // can I declare like this ?????

int main()
{
  apple a;

}
Run Code Online (Sandbox Code Playgroud)

编译此示例时,编译器说:

struct.cpp|11|error: expected ';' before 'a'|
Run Code Online (Sandbox Code Playgroud)

同样的东西在C语言中工作得很好......

怎么了?

CB *_*ley 6

声明了你所做的事情apple,banana并且melon作为全局实例,product而你的main函数表明你想要将它们声明为类型.为此,您将typedef在声明中使用关键字.(虽然为什么你需要这么多同义词struct product?)

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

例如,声明apple,bananamelon作为同义词struct product:

typedef struct product {
  int weight;
  float price;
} apple, banana, melon;
Run Code Online (Sandbox Code Playgroud)