学习C++复合数据类型

复合数据类型

String 类型

char str[20];  //strlen(str)的长度不一定是20

strlen()

cin.getline(str,20);  //读入一行输入(cin是iostream类的一个对象,getline()是iostream类的一个类方法)

使用R来标识原始字符串

cout<<R"(Tom is handsome,\n"this is wrong".)"<<'\n';
//运行结果:Tom is handsome,\n"this is wrong".

C++结构体

#include<iostream>
#include<String>
using namespace std;
struct student
{
	string name;
	string sex;
	int age;
};

int main()
{
	student one=
	{
		"xiaoming",
		"男",
		18,
	}; 
	cout<<one.name+" "<<one.sex+" "<<one.age<<endl;
	return 0;
}

共用体
只能存储其中的一种数据类型(long或char):

	union id
	{
		long id_num;
		char id_char[20];
	} id_val;

假如一些商品的id是字符串,而另一些是整数,就可以用到共用体

//结构体
struct widget{
	char brand[20];
	int type;
	union id
	{
		long id_num;
		char id_char[20];
	} id_val;   //共用体
};
//共用体的使用
widget prize={"笔记本",1};
	if (prize.type==1)
		cin>>prize.id_val.id_num;
	else
	    cin>>prize.id_val.id_char;

枚举

enum spectrum{red,orange,yellow,green,blue,violet,indigo,ultraviolet};

此结构:
enum

spectrum band;
band=blue;  //valid
++band;     //invalid
int color=blue;//valid
band=3;invalid
band=(orange+blue);//invalid
band=spectrum(3); //valid

显式地设置枚举量的值:

enum bits{one=1,two=2,four=4,six=6};

指针和自由存储空间
**
一定要在对指针应用解除应用运算符(*)之前,将指针初始化为一个确定、适当的地址
**

int a=6;
int* b;//指针使用来存储地址的变量
//或者int* b=&a;结果:*b=6,b=&a(a的地址)
b=&a;
cout<<*b;  //6

将数字值作为地址来使用时,需要进行强制转换

int* pt;
pt=(int*)0xB8000000;

使用new来分配内存

int* pn=new int;
*pn=1;
delete pn;//释放内存

使用new来创建动态数组

int* psome=new int[10];
psome[0]=1;
psome[1]=2;
psome[2]=3;
psome=psome+1;
cout<<psome[0]<<psome[1];//结果为2,3;将psome+1后导致它psome[0]指向的是数组的第二个值,即增加sizeof(int)
psome=psome-1;
delete []psome;

指针与数组的关系:

int w[3]={};
int* pw=w;
//数组存在:w=&w[0],即数组首元素的地址
指针的值可以修改,数组名是常量
数组的sizeof得到数组的长度,而指针的到的是指针的长度(8位)
struct people
{
	string name;
	int age;
};

people* ps=new people;
ps->name="xiaoming";
ps->age=18;

类型组合的应用
mixtypes.cpp
与数组相似的vector和array

#include<vector>
#include<array>
using namespace std;
vector<int> vi;
int n;
cin>>n;
vector<double> vd(n);
array<int,5> ai;
array<double,4> ad={1.2,1.3,1.4,1.23};
//array不能使用变量n来创建array
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值