开发者

C++ Structure Declaration and usage compiler error

Here is my code:

#include <iostream>
using namespace std;

struct product {
  int weigh开发者_如何学JAVAt;
  float price;
} apple, banana, melon; // can I declare like this ?????

int main()
{
  apple a;

}

When I compiled this sample, the compiler says:

struct.cpp|11|error: expected ';' before 'a'|

Same thing works fine in C language ...

What's wrong?


What you've done is declared apple, banana and melon as global instances of product whereas your main function indicates that you wanted to declare them as types. To do this you would use the typedef keyword in the declaration. (Although why do you need so many synonyms for struct product?)

This is not different from C. The only difference between C and C++ in your example is that in C++ product names a type whereas in C you have to specify struct product. (Apart from the more obvious fact that you can't have #include <iostream> or using namespace std; in C.)

E.g., declares apple, banana and melon as synonyms for struct product:

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


apple isn't a type, it's a variable of the product struct type you declared.

typedef product apple;

would create a type called apple.


No it doesn't. In C you would write

typedef struct product {
   int weight;
   float price;
} apple;

Note the typedef.


How could the same code run in C? your code will give the same error in C also, it is incorrect.

in the main you have done: apple a where apple is not any type. It is a global struct product type variable.

To define a variable of your structure type do:

int main (void)
{
  struct product a;
}

Or if you want to name your struct with some name you can use typedef like

typedef struct product {
     int weight;
     float price;
} product;

and then

int main (void)
{
  product apple, a, whataver;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜