定义一个结构体Point,如果在C语言里面定义结构体变量时必须添加struct关键字。比如:struct Point pos;如果不添加struct关键字,则报如下错误:
error C2065: 'Point' : undeclared identifier。在C++中就不需要关键字struct。
正确代码:
//比较strcut在C与C++中的异同,C语言 struct Point { int x; int y; }; typedef struct Point_tag { int x; int y; }Point_2D; int main() { struct Point pos; Point_2D pos_2d; pos.x = 5; pos.y = 6; printf("(%d,%d)\n",pos.x,pos.y); pos_2d.x = 8; pos_2d.y = 4; printf("(%d,%d)\n",pos_2d.x,pos_2d.y); return 0; }
错误代码:
//比较strcut在C与C++中的异同,C语言
struct Point
{
int x;
int y;
};
typedef struct Point_tag
{
int x;
int y;
}Point_2D;
int main()
{
Point pos; //错误行
Point_2D pos_2d;
pos.x = 5; pos.y = 6;
printf("(%d,%d)\n",pos.x,pos.y);
pos_2d.x = 8; pos_2d.y = 4;
printf("(%d,%d)\n",pos_2d.x,pos_2d.y);
return 0;
}