[C++ Primer Plus] 第4章、复合类型(一)程序清单——指针new和delete
程序清单4.1
- #include<iostream>
- using namespace std;
- void main(){
- int yams[];
- yams[]=;
- yams[]=;
- yams[]=;
- int yams_cost[]={,,};
- cout<<"Total yams="<<yams[]+yams[]+yams[]<<endl;
- cout<<"The package with "<<yams[]<<" yams costs "<<yams_cost[]<<" cents per yam"<<endl;
- cout<<"Total costs="<<yams[]*yams_cost[]+yams[]*yams_cost[]+yams[]*yams_cost[]<<" cents"<<endl;
- cout<<"Size of yams array="<<sizeof(yams)<<" bytes"<<endl;
- cout<<"Size of yams[0]="<<sizeof(yams[])<<" bytes"<<endl;
- system("pause");
- }
程序清单4.2
- #include<iostream>
- #include<cstring>//strlen(),c语言版为string.h
- using namespace std;
- void main(){
- const int size=;
- char name1[size];//char占一个字节
- char name2[size]="C++owboy";
- cout<<"I am "<<name2<<".What's your name?"<<endl;
- cin>>name1;
- cout<<"Well,"<<name1<<",your name has "<<strlen(name1)<<" letters and is stored in an array of "<<sizeof(name1)<<" bytes"<<endl;
- cout<<"Your initial is "<<name1[]<<endl;
- name2[]='\0';
- cout<<"Here are the first 3 characters of my name:"<<name2<<endl;
- system("pause");
- }
程序清单4.3
- #include<iostream>
- using namespace std;
- void main(){
- const int size=;
- char name[size];
- char dessert[size];
- cout<<"What's your name?"<<endl;
- cin>>name;
- cout<<"What's your favorate dessert?"<<endl;
- cin>>dessert;
- cout<<"I have some delicious "<<dessert<<" for you."<<endl;
- system("pause");
- }
注意:cin使用空白(空格、制表符和换行符)来确定字符串的结束位置,所以cin将Alise放在了name数组,将dreeb放在了dessert数组
为了解决这种问题,C++提供getline()和get()方法,如下所示:
程序清单4.4
- #include<iostream>
- using namespace std;
- void main(){
- const int size=;
- char name[size];
- char dessert[size];
- cout<<"What's your name?"<<endl;
- cin.getline(name,size);
- cout<<"What's your favorate dessert?"<<endl;
- cin.getline(dessert,size);
- cout<<"I have some delicious "<<dessert<<" for you."<<endl;
- system("pause");
- }
程序清单4.6
- #include<iostream>
- using namespace std;
- void main(){
- cout<<"你房子哪一年修的?"<<endl;
- int year;
- cin>>year;
- cout<<"房子的地址?"<<endl;
- char address[];
- cin.getline(address,);
- cout<<"Year built:"<<year<<endl<<"Address:"<<address<<endl<<"Done!";
- system("pause");
- }
用户没有输入地址的机会,问题在于:cin读取年份后,将回车键生成的换行符留在了队列中,后面的cin.getline()看到换行符后,将认为是一个空行。解决如下:
cin>>year;
cin.get();
程序清单4.7(string和数组)
- #include<iostream>
- #include<string>
- using namespace std;
- void main(){
- char ch1[];
- char ch2[]="jaguar";
- string str1;
- string str2="panther";
- cout<<"enter a kind of feline:";
- cin>>ch1;
- cout<<"enter another kind of feline:";
- cin>>str1;
- cout<<"Here are some felines:\n"<<ch1<<" "<<ch2<<" "<<str1<<" "<<str2<<endl;
- cout<<"The third letter in "<<ch2<<" is "<<ch2[]<<endl;
- cout<<"The third letter in "<<str2<<" is "<<str2[]<<endl;
- system("pause");
- }
程序清单4.8(string赋值、拼接和附加)
- #include<iostream>
- #include<string>
- using namespace std;
- void main(){
- string str="penguin";
- string str2,str3,str4;
- str2=str;
- cout<<"str2="<<str2<<endl;
- str3="buzzard";
- cout<<"str3="<<str3<<endl;
- str4=str+str3;
- cout<<"str4="<<str4<<endl;
- str+=str3;
- cout<<"str="<<str<<endl;
- str2+=" is cute!";
- cout<<"str2="<<str2<<endl;
- system("pause");
- }
程序清单4.9(cstring)
- #include<iostream>
- #include<string>
- #include<cstring>//strcpy,strcat,strlen
- using namespace std;
- void main(){
- char ch1[];
- char ch2[]="jaguar";
- string str1;
- string str2="panther";
- str1=str2;
- strcpy(ch1,ch2);
- str1+=" paste";
- strcat(ch1," juice");
- int len1=str1.size();
- int len2=strlen(ch1);
- cout<<"the string "<<str1<<" contains "<<len1<<" characters"<<endl;
- cout<<"the string "<<ch1<<" contains "<<len2<<" characters"<<endl;
- system("pause");
- }
程序清单4.10
- #include<iostream>
- #include<string>
- #include<cstring>
- using namespace std;
- void main(){
- char ch[];
- string str;
- cout<<"Length of string in ch before input:"<<strlen(ch)<<endl;
- cout<<"Length of string in str before input:"<<str.size()<<endl;
- cout<<"Enter a line of text:"<<endl;
- cin.getline(ch,);
- cout<<"You entered:"<<ch<<endl;
- cout<<"Enter another line of text:"<<endl;
- getline(cin,str);
- cout<<"You entered:"<<str<<endl;
- cout<<"Length of string in ch after input:"<<strlen(ch)<<endl;
- cout<<"Length of string in str after input:"<<str.size()<<endl;
- system("pause");
- }
注意:未初始化的数组内容未定,strlen()从数组中的第一个元素开始计算字节数,直到遇到空字符。在本例中数组内并未有空字符,所以字节数甚至超过了数组长度;未初始化的string对象长度置0
程序清单4.11+4.12(结构体)
- #include<iostream>
- using namespace std;
- struct table{
- char name[];
- float volumn;
- double price;
- };
- void main(){
- table guest={"GG",1.88,29.99};
- table pal={"AA",3.12,32.99};
- cout<<"Expand your guest list with "<<guest.name<<" and "<<pal.name<<endl;
- cout<<"You can have both for $"<<guest.price+pal.price<<endl;
- cout<<"------------------------------"<<endl;
- table choice=guest;
- cout<<"choice:"<<choice.name<<" for $"<<choice.price<<endl;
- system("pause");
- }
程序清单4.13
- #include<iostream>
- using namespace std;
- struct table{
- char name[];
- float volumn;
- double price;
- };
- void main(){
- table guest[]={
- {"GG",1.88,29.99},
- {"AA",3.12,32.99}
- };
- cout<<"The guests "<<guest[].name<<" and "<<guest[].name<<endl<<"have a combined volumn of "<<guest[].volumn+guest[].volumn<<" cubic feet"<<endl;
- system("pause");
- }
程序清单4.17(指针:new)
- #include<iostream>
- using namespace std;
- void main(){
- int nights=;
- int *pt = new int;
- *pt = ;
- double *pd = new double;
- *pd = 100000000000.1;
- cout << "nights value=" << nights << ":location " << &nights << endl;
- cout << "int value=" <<*pt<< ":location " <<pt<< endl;
- cout << "double value=" << *pd << ":location " << pd << endl;
- cout << "location of pointer pd:" << &pd<< endl;
- cout << "size of pt=" <<sizeof(pt)<< endl;
- cout << "size of *pt=" << sizeof(*pt) << endl;
- cout << "size of pd=" << sizeof(pd) << endl;
- cout << "size of *pd=" << sizeof(*pd) << endl;
- system("pause");
- }
程序清单4.18(new完之后要delete)
- #include<iostream>
- using namespace std;
- void main() {
- double *p = new double[];//使用new创建动态数组
- p[] = 0.2;
- p[] = 0.5;
- p[] = 0.8;
- cout << "p[1]=" << p[] << endl;
- p++;
- cout << "Now p[0]=" << p[] << endl;
- cout << "p[1]=" << p[] << endl;
- p--;
- cout << "And now p[0]=" << p[] << endl;
- delete[] p;//回归初始位置释放内存
- getchar();
- }
程序清单4.19
- #include<iostream>
- using namespace std;
- void main() {
- double wages[] = { 10000.0,20000.0, 30000.0 };
- short stacks[] = { , , };
- double * pw = wages;
- short * ps = &stacks[];
- cout << "pw=" << pw <<",*pw="<<*pw<< endl;
- pw++;
- cout << "Now,pw=" << pw << ",*pw=" << *pw << endl;
- cout << "ps=" << ps << ",*ps=" << *ps << endl;
- ps++;
- cout << "Now,ps=" << ps << ",*ps=" << *ps << endl;
- cout << "stacks[0]=" << stacks[] << ",stacks[1]=" << stacks[] << endl;
- cout << "*stacks=" << *stacks<< ",*(stacks+1)=" << *(stacks + ) << endl;
- cout << "sizeof(wages)=" << sizeof(wages)<< endl;
- cout << "sizeof(pw)=" << sizeof(pw) << endl;
- getchar();
- }
程序清单4.20
- #define _CRT_SECURE_NO_WARNINGS
- #include<iostream>
- #include<cstring>
- using namespace std;
- void main() {
- char animal[] = "bear";
- const char * bird = "wren";
- char * ps;
- cout << animal <<" and "<< bird << endl;
- cout << "Enter a kind of animal:";
- cin >> animal;
- ps = animal;
- cout << "ps="<<ps<< endl;
- cout << "Before using strcpy(): \n ";
- cout << animal << " at " << (int *)animal << endl;
- cout << ps << " at " << (int *)ps << endl;
- ps = new char[strlen(animal) + ];
- strcpy(ps, animal);
- cout << "After using strcpy(): \n ";
- cout << animal << " at " << (int *)animal << endl;
- cout << ps << " at " << (int *)ps << endl;
- delete[] ps;
- system("pause");
- }
程序清单4.21
- #include<iostream>
- using namespace std;
- struct inflatable {
- char name[];
- float volumn;
- double price;
- };
- void main() {
- inflatable *ps = new inflatable;
- cout <<"Enter name of inflatable item:";
- cin.get(ps->name,);
- cout << "Enter volumn in cubic feet:";
- cin>>(*ps).volumn;
- cout << "Enter price:$";
- cin >>ps->price;
- cout << "Name:" << (*ps).name<< endl;
- cout << "Volumn:" <<ps->volumn<< endl;
- cout << "Price:" <<ps->price<< endl;
- delete ps;
- system("pause");
- }
程序清单4.22
- #include<iostream>
- #include<cstring>
- using namespace std;
- char * getname() {
- char temp[];
- cout << "Enter last name:";
- cin>>temp;
- char *pn = new char[strlen(temp) + ];//长度+1:包括一个空字符
- strcpy(pn, temp);
- return pn;
- }
- void main(){
- char * name;
- name = getname();
- cout << name << " at " << (int *) name << endl;
- delete[] name;
- name = getname();
- cout << name << " at " << (int *) name << endl;
- delete[] name;
- system("pause");
- }
两次地址可能相同,也可能不同。
程序清单4.23(类型组合)
- #include<iostream>
- #include<cstring>
- using namespace std;
- struct Student {
- int age;
- };
- void main(){
- Student s1, s2, s3;
- s1.age = ;
- Student *p = &s2;
- p->age = ;
- Student ss[];
- ss[].age = ;
- cout << "ss[0].age=" << ss->age << endl;
- const Student * arp[] = { &s1,&s2,&s3 };//指针数组:由指针组成的数组
- cout << "s1.age="<<arp[]->age<< endl;
- const Student **ppa = arp;//arp是数组名称,即第一个元素的地址,而第一个元素为指针,所以ppa是二级指针
- auto ppb = arp;//自动推断类型
- cout << "s1.age=" << (*ppa)->age << endl;
- cout << "s2.age=" << (*(ppa+))->age<< endl; //ppa + 1指向arp[1],即&s2
- //cout << "s2.age=" << (*ppa + 1)->age << endl; 错误!
- system("pause");
- }
程序清单4.24(数组的替代品,array,vector)
- #include<iostream>
- #include<vector>
- #include<array>
- using namespace std;
- void main() {
- double a[] = { 1.2,2.4,3.6,4.8 };
- vector<double> b();
- b[] = 1.0 / 3.0;
- b[] = 1.0 / 5.0;
- b[] = 1.0 / 7.0;
- b[] = 1.0 / 9.0;
- array<double, > c = { 3.14,2.72,1.62,1.41 };
- array<double, > d;
- d = c;
- cout << "a[2]:" << a[] << " at " << &a[]<< endl;//&a[2]=a + 2
- cout << "b[2]:" << b[] << " at " << &b[] << endl;
- cout << "c[2]:" << c[] << " at " << &c[] << endl;
- cout << "d[2]:" << d[] << " at " << &d[] << endl<<endl;
- a[-] = 20.2;//a[-2]=*(a-2)
- cout << "a[2]:" << a[-]<< " at " << &a[-]<< endl;
- cout << "c[2]:" << c[] << " at " << &c[] << endl;
- cout << "d[2]:" << d[] << " at " << &d[] << endl;
- system("pause");
- }
注意:无论是数组,vector还是array对象,都可以使用数组表示法来访问各个元素。其次,从地址可知,array和数组都是存储在栈中,而vector存储在自由存储区或堆中。第三,可以将array对象赋给另一个array对象;而对于数组,必须逐元素复制。
- 索引-2转换为:a[-2]=*(a-2)
[C++ Primer Plus] 第4章、复合类型(一)程序清单——指针new和delete的更多相关文章
- C++ Primer Plus 第四章 复合类型 学习笔记
第四章 复合类型 1. 数组概述 1.1 数组的定义 数组(array)是一种数据格式,能够存储多个同类型的值.每个值都存储在一个独立的数组元素中,计算机在内存中依次存储数组的各个元素. 数组声明的三 ...
- C++ primer plus读书笔记——第4章 复合类型
第4章 复合类型 1. 如果将sizeof运算符用于数组名,得到的将是整个数组中的字节数. 2. 如果对数组的一部分进行初始化,则编译器把其他元素设置为0.因此,将数组中的所有元素初始化为0,只要显式 ...
- C++PrimerPlus第6版 第四章——复合类型
1,复合类型主要包含:数组.结构.联合.枚举.类.指针.引用等. 2,数组.长度必须确定.即编译阶段,数组的长度就得确定好.所以只能使用常量(#define.const)声明数组长度.如果使用变量声明 ...
- C++ Primer : 第十二章 : 动态内存之动态内存管理(new和delete)
C++语言定义了两个运算符来分配和释放动态内存:运算符new分配内存,运算符delete释放new分配的内存. 运算符new和delete 使用new动态分配和初始化对象 在自由空间分配的内存是无名的 ...
- [C++ Primer Plus] 第5章、循环和关系表达式(一)程序清单——指针自加减优先级
程序5.4 #include<iostream> using namespace std; ; void main() { long long factorials[Size]; fact ...
- 《C++ Primer Plus》读书笔记之二—复合类型
二.第四章 复合类型 1.C-风格字符串:C-风格字符串具有一种特殊的性质:以空字符结尾,空字符被写成\0,其ASC||编码为0,用来标记字符串的结尾.例如: char dog[5]={'b','e ...
- C++Primer快速浏览笔记-复合类型
C++Primer2.3节介绍了两种复合类型:引用和指针 1.引用 引用并非对象,它只是为一个已经存在的对象所起的别名. 一旦初始化完成,引用将和它的初始值对象一直绑定在一起,不能重新绑定到另一个对象 ...
- c++中的复合类型
复合类型是指基于其他类型而定义的类型. 而这里介绍的是引用和指针.并且指针和引用都提供了对其他对象的间接访问. 引用 引用还是很好理解的,就是为对象起了另外一个名字,引用类型引用另外一种类型. 通常将 ...
- 学习C++.Primer.Plus 4 复合类型
本章介绍的有复合类型有: 数组. 字符串. 结构. 共用体. 指针 数组: 声明数组时数组长度必须为常量(或const). 只有初始化时可以用“=”,其它时候均不可以给数组直接赋值,除了赋值的元素以外 ...
随机推荐
- 以太坊: ETH 发送交易 sendRawTransaction 方法数据的签名 和 验证过程
作者:林冠宏 / 指尖下的幽灵 掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8 博客:http://www.cnblogs.com/linguan ...
- Hello 博客!
2018-4-9 18:11:05第一次听这个python视频教程 然后让做的博客!放张图!
- ruby 知识点随笔
print .puts 和 p 方法的区别."" 与 '' 的区别. 处理控制台编码问题 >ruby -E utf-8 脚本文件名称 # 执行脚本 >irb -E u ...
- Spring AOP 随记
本周经历各种面试失败后,最后一站张建飞老大的阿里,感觉有着这般年纪不该有的垃圾履历而忧伤中,不过还是要继续加油的,毕竟他说的好,都是经历,无愧初心. 所以为了更加深入理解Spring AOP我又翻起了 ...
- meta标签大全(荐)
html的meta总结(常用) 1.Meta标签大全 <!-- 声明文档使用的字符编码 --> <meta charset='utf-8'> <!-- 优先使用 IE 最 ...
- HTML02单词
form:表单action:行动(提交的路径)method:方法(提交的方式)input:输入type:类型text:文本(文本输入项)password:密码radio:单选按钮checkbox:复选 ...
- FTPService工具类
package com.vcredit.ddcash.server.commons.net; import com.vcredit.ddcash.server.commons.model.FtpPar ...
- VAE (variational autoencoder)
https://www.zhihu.com/question/41490383/answer/103006793 自编码是一种表示学习的技术,是deep learning的核心问题 让输入等于输出,取 ...
- grep匹配字符串
基本正则表达式 元数据 意义和范例 ^word 搜寻以word开头的行. 例如:搜寻以#开头的脚本注释行 grep –n ‘^#’ regular.txt word$ 搜寻以word结束的行 例如,搜 ...
- SpringBoot-将servlet容器变成undertow测试tomcat吞吐量
将Servlet容器变成Undertow 默认情况下,Spring Boot 使用 Tomcat 来作为内嵌的 Servlet 容器 可以将 Web 服务器切换到 Undertow 来提高应用性能.U ...