3.3 数组及自定义数据类型 【C++】

#include "stdafx.h"
// Demo.cpp : 定义控制台应用程序的入口点。
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>   //向量
using namespace std;
#if 1
//结构体
struct Student {    // 255 + 4 + 4 = 263  处理:以4整数倍   ==》 264
	 //  3个属性 attribute
	 char sName[255];   
	 int iHeight;
	 float fWeight;   
};
int main(void) {
 	Student a1;
	// Student a2;
	// Student a1 ={"Tom Henry", 172, 66.7 };  //初始化
 	strcpy_s(a1.sName, "Tom Henry");
	// a1.sName = "Tom Henry";   // 不能直接赋值  这里会出错
	a1.iHeight = 175;
	a1.fWeight = 120.2;
	// a2.iHeight = 172;
	cout << "sizeof(a1):" << sizeof(a1) << endl;   // 结果是 264
	cout << a1.sName << endl;
}
#endif
#include "stdafx.h"
// Demo.cpp : 定义控制台应用程序的入口点。
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>   //向量
using namespace std;
#if 1
union Dummy {     // 联合
	 char c;
	 int i;
	 float f;
};
int main(void) {
	 Dummy a;
	 // 三个地址是一样的
	 cout << "addr of a.c:" << (int)&a.c << endl;
	 cout << "addr of a.i:" << (int)&a.i << endl;
	 cout << "addr of a.f:" << (int)&a.f << endl;
	 
	 // 以三个成员最大的内存大小    为4
	 cout << "sizeof dummy:" << sizeof(Dummy) << endl;    //4 
	 cout << "sizeof a:" << sizeof(a) << endl;   // 4

	// 这里先赋值的a.c和a.i会被a.f覆盖掉
	 a.c = '0';
	 a.i = 1000;
	 a.f = 999.99;
	 cout << "a.c:" << a.c << "a.i:" << a.i << "a.f:" << a.f << endl;
	 return 0;
 }
 #endif
发布了41 篇原创文章 · 获赞 1 · 访问量 475

猜你喜欢

转载自blog.csdn.net/weixin_44773006/article/details/103506966
今日推荐