C++之数据类型的扩展

📅 发布时间:2026/7/7 6:36:36 👁️ 浏览次数:
C++之数据类型的扩展
文章目录结构体联合体枚举布尔字符串string类型字符串定义字符串拷贝字符串连接字符串比较随机访问获取字符串长度转换为C风格的字符串字符串交换demo结构体C中定义结构型变量可以省略struct关键字C结构体中可以直接定义函数谓之成员函数方法#includeiostream#includecstringusing namespace std;intmain(void){structstu{intage;charname[20];voidwho(void){cout我是name 我今年ageendl;}};stu s1;s1.age21;strcpy(s1.name,张飞);s1.who();return0;}联合体C中定义联合体变量可以省略union关键字unionXX{……};XX x;//定义联合体变量直接省略union支持匿名联合union//没有名字……};#includeiostreamusingnamespacestd;intmain(void){union{//匿名联合intnum;charc[4];};num0x12345678;couthex(int)c[0] (int)c[1]endl;return0;}枚举C中定义枚举变量可以省略enum关键字C中枚举是独立的数据类型不能当做整型数使用#includeiostreamusingnamespacestd;intmain(void){enumCOLOR{RED,GREEN,BLUE};COLOR cGREEN;//c 2; //errorcoutcendl;return0;}布尔C中布尔(bool)是基本数据类型专门表示逻辑值布尔类型的字面值常量true 表示逻辑真false表示逻辑假布尔类型的本质 单字节的整数使用1表示真0表示假任何基本类型都可以被隐式转换为布尔类型#includeiostreamusingnamespacestd;intmain(void){boolbtrue;coutbendl;coutboolalphabendl;b32;coutboolalphabendl;return0;}字符串C兼容C中的字符串表示方法和操作函数C专门设计了string类型表示字符串string类型字符串定义string s;//定义空字符串strings(hello);string shello;string sstring(hello);字符串拷贝string s1“hello”;string s2s1;字符串连接string s1“hello”,s2“ world”;string s3s1s2;//s3:hello worlds1s2;//s1:hello world字符串比较string s1“hello”,s2“ world”;if(s1s2){cout“false”endl;}if(s1!s2){cout“true”endl;}随机访问string s“hello”;s[0]“H”;//Hello获取字符串长度size_tsize();size_tlength();转换为C风格的字符串constchar*c_str();字符串交换voidswap(string s1,string s2);demo#includeiostream#includecstdiousingnamespacestd;intmain(){/*定义*/string s1;//定义空字符串strings2(aaa);string s3string(bbb);string s4cccc;/*字符串的拷贝*/string s5s2;// char *p5 p2;couts5 s5endl;/*拼接*/s5s3;couts5 s5endl;/*字符串比较*/if(s2s3){//strcmp(.....)couttrueendl;}else{coutfalseendl;}/*取字符串长度*/couts5 length s5.length()endl;/*转换为C风格字符串*/constchar*ps5.c_str();printf(%s\n,p);/*交换*/swap(s2,s3);couts2 s2 s3 s3endl;return0;}