标准C++程序设计学习笔记(三)——C++的结构体、联合和枚举

2021/9/19 22:05:00

本文主要是介绍标准C++程序设计学习笔记(三)——C++的结构体、联合和枚举,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

结构体

  • C++中在使用结构体时,直接可以省略struct关键字

  • sizeof(空结构体) C++结果为1 C语言为0

#include <stdio.h>    //11struct.c


struct Stu{
	
};


int main(){
	struct Stu s;
	printf("%u\n",sizeof(s));
	return 0;	
}

 

#include <iostream>    //12struct.cpp
using namespace std;

struct Stu{
	
};

int main(){
	Stu s = {};
	cout << sizeof(s) << endl;
	return 0;	
}
  • C++结构体重可以定义函数,结构体中的函数可以直接访问成员

    • C++结构体中的函数,是用C结构体中可以定义函数指针的方式实现

  • C++结构体中可以有构造函数

#include <iostream>    //13struct.cpp
using namespace std;

//面向对象的编程思想    C++用C语言的实现   C语言中虽然没有函数,但是可以有函数指针
struct Date{
	int year;
	int mon;
	int day;
	//在结构体内部定义函数 可以直接访问结构体中的成员变量
	void show(){
		cout << year << "-" << mon << "-" << day << endl;	
	}
};


int main(){
	Date d = {2021,8,24};
	d.show();
	Date d1 = {2008,8,8};
	d1.show();
	cin >> d1.year >> d1.mon >> d1.day;
	return 0;	
}

联合

  • C++中支持匿名联合。

  • 借用联合的语法形式,描述变量在内存中的布局方式

  • 匿名联合的变量,可以直接访问,不需要定义联合变量

#include <iostream>    //14union.cpp
using namespace std;


int main(){
	//匿名联合  相当于定义了两个变量u1,c1  
	//匿名联合中的变量内存是共享的
	union{
		int u1;
		char c1;
	};
	
	u1 = 0x12345678;
	cout << hex << (int)c1 << endl;

	int u2;
	char c2;
	return 0;	
}

枚举

  • C++中的枚举是一种独立的类型 不能直接用整数值赋值给枚举变量

  • 依然允许枚举变量/枚举值赋值给整数变量

#include <iostream>    //15enum.cpp
using namespace std;

enum Dire{UP,DO,LE,RI};

int main(){
	Dire d = UP;
	d = DO;
	//d = 0;//不能用整数给枚举变量赋值
	cout << UP << endl;//UP的值等于0   d=0;不允许 C++加强了类型检查

	int x = UP;
	x = d;//枚举变量和枚举值可以赋值给整数
	cout << x << endl;

	return 0;	
}



这篇关于标准C++程序设计学习笔记(三)——C++的结构体、联合和枚举的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程