程序清单4.1

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void main(){
  5. int yams[];
  6. yams[]=;
  7. yams[]=;
  8. yams[]=;
  9. int yams_cost[]={,,};
  10.  
  11. cout<<"Total yams="<<yams[]+yams[]+yams[]<<endl;
  12. cout<<"The package with "<<yams[]<<" yams costs "<<yams_cost[]<<" cents per yam"<<endl;
  13. cout<<"Total costs="<<yams[]*yams_cost[]+yams[]*yams_cost[]+yams[]*yams_cost[]<<" cents"<<endl;
  14.  
  15. cout<<"Size of yams array="<<sizeof(yams)<<" bytes"<<endl;
  16. cout<<"Size of yams[0]="<<sizeof(yams[])<<" bytes"<<endl;
  17.  
  18. system("pause");
  19. }

程序清单4.2

  1. #include<iostream>
  2. #include<cstring>//strlen(),c语言版为string.h
  3. using namespace std;
  4.  
  5. void main(){
  6. const int size=;
  7. char name1[size];//char占一个字节
  8. char name2[size]="C++owboy";
  9.  
  10. cout<<"I am "<<name2<<".What's your name?"<<endl;
  11. cin>>name1;
  12. cout<<"Well,"<<name1<<",your name has "<<strlen(name1)<<" letters and is stored in an array of "<<sizeof(name1)<<" bytes"<<endl;
  13. cout<<"Your initial is "<<name1[]<<endl;
  14. name2[]='\0';
  15. cout<<"Here are the first 3 characters of my name:"<<name2<<endl;
  16. system("pause");
  17. }

程序清单4.3

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void main(){
  5. const int size=;
  6. char name[size];
  7. char dessert[size];
  8.  
  9. cout<<"What's your name?"<<endl;
  10. cin>>name;
  11. cout<<"What's your favorate dessert?"<<endl;
  12. cin>>dessert;
  13. cout<<"I have some delicious "<<dessert<<" for you."<<endl;
  14. system("pause");
  15. }

注意:cin使用空白(空格、制表符和换行符)来确定字符串的结束位置,所以cin将Alise放在了name数组,将dreeb放在了dessert数组

为了解决这种问题,C++提供getline()和get()方法,如下所示:

程序清单4.4

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void main(){
  5. const int size=;
  6. char name[size];
  7. char dessert[size];
  8.  
  9. cout<<"What's your name?"<<endl;
  10. cin.getline(name,size);
  11. cout<<"What's your favorate dessert?"<<endl;
  12. cin.getline(dessert,size);
  13. cout<<"I have some delicious "<<dessert<<" for you."<<endl;
  14. system("pause");
  15. }

程序清单4.6

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void main(){
  5. cout<<"你房子哪一年修的?"<<endl;
  6. int year;
  7. cin>>year;
  8. cout<<"房子的地址?"<<endl;
  9. char address[];
  10. cin.getline(address,);
  11. cout<<"Year built:"<<year<<endl<<"Address:"<<address<<endl<<"Done!";
  12. system("pause");
  13. }

用户没有输入地址的机会,问题在于:cin读取年份后,将回车键生成的换行符留在了队列中,后面的cin.getline()看到换行符后,将认为是一个空行。解决如下:

  cin>>year;

  cin.get();

程序清单4.7(string和数组)

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4.  
  5. void main(){
  6. char ch1[];
  7. char ch2[]="jaguar";
  8. string str1;
  9. string str2="panther";
  10.  
  11. cout<<"enter a kind of feline:";
  12. cin>>ch1;
  13. cout<<"enter another kind of feline:";
  14. cin>>str1;
  15. cout<<"Here are some felines:\n"<<ch1<<" "<<ch2<<" "<<str1<<" "<<str2<<endl;
  16. cout<<"The third letter in "<<ch2<<" is "<<ch2[]<<endl;
  17. cout<<"The third letter in "<<str2<<" is "<<str2[]<<endl;
  18. system("pause");
  19. }

程序清单4.8(string赋值、拼接和附加)

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4.  
  5. void main(){
  6. string str="penguin";
  7. string str2,str3,str4;
  8.  
  9. str2=str;
  10. cout<<"str2="<<str2<<endl;
  11. str3="buzzard";
  12. cout<<"str3="<<str3<<endl;
  13. str4=str+str3;
  14. cout<<"str4="<<str4<<endl;
  15. str+=str3;
  16. cout<<"str="<<str<<endl;
  17. str2+=" is cute!";
  18. cout<<"str2="<<str2<<endl;
  19. system("pause");
  20. }

程序清单4.9(cstring)

  1. #include<iostream>
  2. #include<string>
  3. #include<cstring>//strcpy,strcat,strlen
  4. using namespace std;
  5.  
  6. void main(){
  7. char ch1[];
  8. char ch2[]="jaguar";
  9. string str1;
  10. string str2="panther";
  11.  
  12. str1=str2;
  13. strcpy(ch1,ch2);
  14.  
  15. str1+=" paste";
  16. strcat(ch1," juice");
  17.  
  18. int len1=str1.size();
  19. int len2=strlen(ch1);
  20.  
  21. cout<<"the string "<<str1<<" contains "<<len1<<" characters"<<endl;
  22. cout<<"the string "<<ch1<<" contains "<<len2<<" characters"<<endl;
  23.  
  24. system("pause");
  25. }

程序清单4.10

  1. #include<iostream>
  2. #include<string>
  3. #include<cstring>
  4. using namespace std;
  5.  
  6. void main(){
  7. char ch[];
  8. string str;
  9.  
  10. cout<<"Length of string in ch before input:"<<strlen(ch)<<endl;
  11. cout<<"Length of string in str before input:"<<str.size()<<endl;
  12. cout<<"Enter a line of text:"<<endl;
  13. cin.getline(ch,);
  14. cout<<"You entered:"<<ch<<endl;
  15. cout<<"Enter another line of text:"<<endl;
  16. getline(cin,str);
  17. cout<<"You entered:"<<str<<endl;
  18. cout<<"Length of string in ch after input:"<<strlen(ch)<<endl;
  19. cout<<"Length of string in str after input:"<<str.size()<<endl;
  20.  
  21. system("pause");
  22. }

注意:未初始化的数组内容未定,strlen()从数组中的第一个元素开始计算字节数,直到遇到空字符。在本例中数组内并未有空字符,所以字节数甚至超过了数组长度;未初始化的string对象长度置0

程序清单4.11+4.12(结构体)

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. struct table{
  5. char name[];
  6. float volumn;
  7. double price;
  8. };
  9.  
  10. void main(){
  11. table guest={"GG",1.88,29.99};
  12. table pal={"AA",3.12,32.99};
  13. cout<<"Expand your guest list with "<<guest.name<<" and "<<pal.name<<endl;
  14. cout<<"You can have both for $"<<guest.price+pal.price<<endl;
  15.  
  16. cout<<"------------------------------"<<endl;
  17.  
  18. table choice=guest;
  19. cout<<"choice:"<<choice.name<<" for $"<<choice.price<<endl;
  20.  
  21. system("pause");
  22. }

程序清单4.13

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. struct table{
  5. char name[];
  6. float volumn;
  7. double price;
  8. };
  9.  
  10. void main(){
  11. table guest[]={
  12. {"GG",1.88,29.99},
  13. {"AA",3.12,32.99}
  14. };
  15. cout<<"The guests "<<guest[].name<<" and "<<guest[].name<<endl<<"have a combined volumn of "<<guest[].volumn+guest[].volumn<<" cubic feet"<<endl;
  16.  
  17. system("pause");
  18. }

程序清单4.17(指针:new)

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void main(){
  5. int nights=;
  6. int *pt = new int;
  7. *pt = ;
  8. double *pd = new double;
  9. *pd = 100000000000.1;
  10.  
  11. cout << "nights value=" << nights << ":location " << &nights << endl;
  12. cout << "int value=" <<*pt<< ":location " <<pt<< endl;
  13. cout << "double value=" << *pd << ":location " << pd << endl;
  14. cout << "location of pointer pd:" << &pd<< endl;
  15.  
  16. cout << "size of pt=" <<sizeof(pt)<< endl;
  17. cout << "size of *pt=" << sizeof(*pt) << endl;
  18. cout << "size of pd=" << sizeof(pd) << endl;
  19. cout << "size of *pd=" << sizeof(*pd) << endl;
  20.  
  21. system("pause");
  22. }

程序清单4.18(new完之后要delete)

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void main() {
  5. double *p = new double[];//使用new创建动态数组
  6. p[] = 0.2;
  7. p[] = 0.5;
  8. p[] = 0.8;
  9. cout << "p[1]=" << p[] << endl;
  10. p++;
  11. cout << "Now p[0]=" << p[] << endl;
  12. cout << "p[1]=" << p[] << endl;
  13. p--;
  14. cout << "And now p[0]=" << p[] << endl;
  15. delete[] p;//回归初始位置释放内存
  16. getchar();
  17. }

程序清单4.19

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void main() {
  5. double wages[] = { 10000.0,20000.0, 30000.0 };
  6. short stacks[] = { , , };
  7. double * pw = wages;
  8. short * ps = &stacks[];
  9.  
  10. cout << "pw=" << pw <<",*pw="<<*pw<< endl;
  11. pw++;
  12. cout << "Now,pw=" << pw << ",*pw=" << *pw << endl;
  13. cout << "ps=" << ps << ",*ps=" << *ps << endl;
  14. ps++;
  15. cout << "Now,ps=" << ps << ",*ps=" << *ps << endl;
  16.  
  17. cout << "stacks[0]=" << stacks[] << ",stacks[1]=" << stacks[] << endl;
  18. cout << "*stacks=" << *stacks<< ",*(stacks+1)=" << *(stacks + ) << endl;
  19. cout << "sizeof(wages)=" << sizeof(wages)<< endl;
  20. cout << "sizeof(pw)=" << sizeof(pw) << endl;
  21.  
  22. getchar();
  23. }

程序清单4.20

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<cstring>
  4. using namespace std;
  5.  
  6. void main() {
  7. char animal[] = "bear";
  8. const char * bird = "wren";
  9. char * ps;
  10.  
  11. cout << animal <<" and "<< bird << endl;
  12. cout << "Enter a kind of animal:";
  13. cin >> animal;
  14. ps = animal;
  15. cout << "ps="<<ps<< endl;
  16. cout << "Before using strcpy(): \n ";
  17. cout << animal << " at " << (int *)animal << endl;
  18. cout << ps << " at " << (int *)ps << endl;
  19.  
  20. ps = new char[strlen(animal) + ];
  21. strcpy(ps, animal);
  22. cout << "After using strcpy(): \n ";
  23. cout << animal << " at " << (int *)animal << endl;
  24. cout << ps << " at " << (int *)ps << endl;
  25. delete[] ps;
  26.  
  27. system("pause");
  28. }

程序清单4.21

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. struct inflatable {
  5. char name[];
  6. float volumn;
  7. double price;
  8. };
  9.  
  10. void main() {
  11. inflatable *ps = new inflatable;
  12.  
  13. cout <<"Enter name of inflatable item:";
  14. cin.get(ps->name,);
  15. cout << "Enter volumn in cubic feet:";
  16. cin>>(*ps).volumn;
  17. cout << "Enter price:$";
  18. cin >>ps->price;
  19.  
  20. cout << "Name:" << (*ps).name<< endl;
  21. cout << "Volumn:" <<ps->volumn<< endl;
  22. cout << "Price:" <<ps->price<< endl;
  23. delete ps;
  24.  
  25. system("pause");
  26. }

程序清单4.22

  1. #include<iostream>
  2. #include<cstring>
  3. using namespace std;
  4.  
  5. char * getname() {
  6. char temp[];
  7. cout << "Enter last name:";
  8. cin>>temp;
  9. char *pn = new char[strlen(temp) + ];//长度+1:包括一个空字符
  10. strcpy(pn, temp);
  11. return pn;
  12. }
  13.  
  14. void main(){
  15. char * name;
  16. name = getname();
  17. cout << name << " at " << (int *) name << endl;
  18. delete[] name;
  19.  
  20. name = getname();
  21. cout << name << " at " << (int *) name << endl;
  22. delete[] name;
  23.  
  24. system("pause");
  25. }

两次地址可能相同,也可能不同。

程序清单4.23(类型组合)

  1. #include<iostream>
  2. #include<cstring>
  3. using namespace std;
  4.  
  5. struct Student {
  6. int age;
  7. };
  8.  
  9. void main(){
  10. Student s1, s2, s3;
  11. s1.age = ;
  12. Student *p = &s2;
  13. p->age = ;
  14. Student ss[];
  15. ss[].age = ;
  16.  
  17. cout << "ss[0].age=" << ss->age << endl;
  18.  
  19. const Student * arp[] = { &s1,&s2,&s3 };//指针数组:由指针组成的数组
  20. cout << "s1.age="<<arp[]->age<< endl;
  21.  
  22. const Student **ppa = arp;//arp是数组名称,即第一个元素的地址,而第一个元素为指针,所以ppa是二级指针
  23. auto ppb = arp;//自动推断类型
  24. cout << "s1.age=" << (*ppa)->age << endl;
  25. cout << "s2.age=" << (*(ppa+))->age<< endl; //ppa + 1指向arp[1],即&s2
  26. //cout << "s2.age=" << (*ppa + 1)->age << endl; 错误!
  27.  
  28. system("pause");
  29. }

程序清单4.24(数组的替代品,array,vector)

  1. #include<iostream>
  2. #include<vector>
  3. #include<array>
  4. using namespace std;
  5.  
  6. void main() {
  7. double a[] = { 1.2,2.4,3.6,4.8 };
  8. vector<double> b();
  9. b[] = 1.0 / 3.0;
  10. b[] = 1.0 / 5.0;
  11. b[] = 1.0 / 7.0;
  12. b[] = 1.0 / 9.0;
  13. array<double, > c = { 3.14,2.72,1.62,1.41 };
  14. array<double, > d;
  15. d = c;
  16.  
  17. cout << "a[2]:" << a[] << " at " << &a[]<< endl;//&a[2]=a + 2
  18. cout << "b[2]:" << b[] << " at " << &b[] << endl;
  19. cout << "c[2]:" << c[] << " at " << &c[] << endl;
  20. cout << "d[2]:" << d[] << " at " << &d[] << endl<<endl;
  21.  
  22. a[-] = 20.2;//a[-2]=*(a-2)
  23. cout << "a[2]:" << a[-]<< " at " << &a[-]<< endl;
  24. cout << "c[2]:" << c[] << " at " << &c[] << endl;
  25. cout << "d[2]:" << d[] << " at " << &d[] << endl;
  26.  
  27. system("pause");
  28. }

注意:无论是数组,vector还是array对象,都可以使用数组表示法来访问各个元素。其次,从地址可知,array和数组都是存储在栈中,而vector存储在自由存储区或堆中。第三,可以将array对象赋给另一个array对象;而对于数组,必须逐元素复制。

  1. 索引-2转换为:a[-2]=*(a-2)

[C++ Primer Plus] 第4章、复合类型(一)程序清单——指针new和delete的更多相关文章

  1. C++ Primer Plus 第四章 复合类型 学习笔记

    第四章 复合类型 1. 数组概述 1.1 数组的定义 数组(array)是一种数据格式,能够存储多个同类型的值.每个值都存储在一个独立的数组元素中,计算机在内存中依次存储数组的各个元素. 数组声明的三 ...

  2. C++ primer plus读书笔记——第4章 复合类型

    第4章 复合类型 1. 如果将sizeof运算符用于数组名,得到的将是整个数组中的字节数. 2. 如果对数组的一部分进行初始化,则编译器把其他元素设置为0.因此,将数组中的所有元素初始化为0,只要显式 ...

  3. C++PrimerPlus第6版 第四章——复合类型

    1,复合类型主要包含:数组.结构.联合.枚举.类.指针.引用等. 2,数组.长度必须确定.即编译阶段,数组的长度就得确定好.所以只能使用常量(#define.const)声明数组长度.如果使用变量声明 ...

  4. C++ Primer : 第十二章 : 动态内存之动态内存管理(new和delete)

    C++语言定义了两个运算符来分配和释放动态内存:运算符new分配内存,运算符delete释放new分配的内存. 运算符new和delete 使用new动态分配和初始化对象 在自由空间分配的内存是无名的 ...

  5. [C++ Primer Plus] 第5章、循环和关系表达式(一)程序清单——指针自加减优先级

    程序5.4 #include<iostream> using namespace std; ; void main() { long long factorials[Size]; fact ...

  6. 《C++ Primer Plus》读书笔记之二—复合类型

    二.第四章 复合类型  1.C-风格字符串:C-风格字符串具有一种特殊的性质:以空字符结尾,空字符被写成\0,其ASC||编码为0,用来标记字符串的结尾.例如: char dog[5]={'b','e ...

  7. C++Primer快速浏览笔记-复合类型

    C++Primer2.3节介绍了两种复合类型:引用和指针 1.引用 引用并非对象,它只是为一个已经存在的对象所起的别名. 一旦初始化完成,引用将和它的初始值对象一直绑定在一起,不能重新绑定到另一个对象 ...

  8. c++中的复合类型

    复合类型是指基于其他类型而定义的类型. 而这里介绍的是引用和指针.并且指针和引用都提供了对其他对象的间接访问. 引用 引用还是很好理解的,就是为对象起了另外一个名字,引用类型引用另外一种类型. 通常将 ...

  9. 学习C++.Primer.Plus 4 复合类型

    本章介绍的有复合类型有: 数组. 字符串. 结构. 共用体. 指针 数组: 声明数组时数组长度必须为常量(或const). 只有初始化时可以用“=”,其它时候均不可以给数组直接赋值,除了赋值的元素以外 ...

随机推荐

  1. 以太坊: ETH 发送交易 sendRawTransaction 方法数据的签名 和 验证过程

    作者:林冠宏 / 指尖下的幽灵 掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8 博客:http://www.cnblogs.com/linguan ...

  2. Hello 博客!

    2018-4-9 18:11:05第一次听这个python视频教程 然后让做的博客!放张图!

  3. ruby 知识点随笔

    print .puts 和 p 方法的区别."" 与 ''  的区别. 处理控制台编码问题 >ruby -E utf-8 脚本文件名称 # 执行脚本 >irb -E u ...

  4. Spring AOP 随记

    本周经历各种面试失败后,最后一站张建飞老大的阿里,感觉有着这般年纪不该有的垃圾履历而忧伤中,不过还是要继续加油的,毕竟他说的好,都是经历,无愧初心. 所以为了更加深入理解Spring AOP我又翻起了 ...

  5. meta标签大全(荐)

    html的meta总结(常用) 1.Meta标签大全 <!-- 声明文档使用的字符编码 --> <meta charset='utf-8'> <!-- 优先使用 IE 最 ...

  6. HTML02单词

    form:表单action:行动(提交的路径)method:方法(提交的方式)input:输入type:类型text:文本(文本输入项)password:密码radio:单选按钮checkbox:复选 ...

  7. FTPService工具类

    package com.vcredit.ddcash.server.commons.net; import com.vcredit.ddcash.server.commons.model.FtpPar ...

  8. VAE (variational autoencoder)

    https://www.zhihu.com/question/41490383/answer/103006793 自编码是一种表示学习的技术,是deep learning的核心问题 让输入等于输出,取 ...

  9. grep匹配字符串

    基本正则表达式 元数据 意义和范例 ^word 搜寻以word开头的行. 例如:搜寻以#开头的脚本注释行 grep –n ‘^#’ regular.txt word$ 搜寻以word结束的行 例如,搜 ...

  10. SpringBoot-将servlet容器变成undertow测试tomcat吞吐量

    将Servlet容器变成Undertow 默认情况下,Spring Boot 使用 Tomcat 来作为内嵌的 Servlet 容器 可以将 Web 服务器切换到 Undertow 来提高应用性能.U ...