struct 结构体在 c和 c++ 中的不同使用方法

1.C 中 struct 的常见使用方法

//第一种方法
//定义
struct Mystruct{
	int x;
	int y;
}ms1;		//同时定义了变量ms1

//使用
struct Mystruct ms2;		//必须加struct
ms1.x = 1;
ms1.y = 2;

ms2.x = 3;
ms2.y = 4;
//第二种方法
//定义
typedef struct Mystruct{
	int x;
	int y;
}Mystruct2 ,*PMystruct;

//使用
struct Mystruct ms1;
Mystruct2	ms2; 		//Mystruct2 是类型,相当于struct Mystruct
PMystruct   pms = &ms2;	//PMystruct 是指向struct Mystruct类型对象的指针
ms1.x = 1;
ms1.y = 2;

ms2.x = 3;
ms2.y = 4;


2.C++ 中 struct 的使用方法

//首先,c++ 兼容上面c中的语法
//不过c++ 中使用的方法更简便
//定义
struct Mystruct{
	int x;
	int y;
}ms1;		//同时定义了变量ms1

Mystruct ms2;	//与c对比,此处可以省略 struct
ms1.x = 1;
ms1.y = 2;

ms2.x = 3;
ms2.y = 4;
//第二,c++ 中的struct可以放成员函数,并且与class的使用基本一致;
//区别在于 如果不指名权限,那么所有成员都是public的
struct Mystruct{
	int x;
	int y;
	void setz(int x);
	int  getz(void);
private:
	int z;
};		
Mystruct ms;
ms.x = 1;
ms.y = 2;
//ms.z = 3; //编译报错 无法访问 private 成员
ms.setz(3);
int z = ms.getz();	//z = 3 


struct 的其他使用方法

//匿名struct
struct {
	int x;
	int y;
}ms1;
ms1.x = 1;
ms1.y = 2;
//ms1可以正常使用,但是只能在声明时定义此类对象 ,以后再无法定义


//匿名typedef struct
typedef struct{
	int x;
	int y;
}Mystruct;
Mystruct ms1;
//不影响使用
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值