结构体在C与C++中的异同

定义一个结构体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;
}

但是如代码中所示,使用typedef 重定义,则在定义变量时就不需要struct关键字。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值