[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). 只有初始化时可以用“=”,其它时候均不可以给数组直接赋值,除了赋值的元素以外 ...
随机推荐
- vue文件中引入外部js
1.在项目的入口文件中(app.js)定义remoteScript标签 Vue.component('remote-script', { render: function (createElement ...
- centos7 与 archlinux用户 安装 python3模块 pytaglib
对于 centos7用户: yum group install "Development Tools" yum install taglib-devel yum install p ...
- layui封装自定义模块
转自:https://lianghongbo.cn/blog/430585105a35948c layui是国人开发的一款非常简洁的UI框架,使用了模块化加载方式,因此在使用过程中我们难免需要添加自己 ...
- python换行语法错误
a ={ ('住宅', 'https://auction.jd.com/getJudicatureList.html?callback=jQuery4392669&page=1&lim ...
- SpringMVC访问静态资源的三种方式
如何你的DispatcherServlet拦截 *.do这样的URL,就不存在访问不到静态资源的问题.如果你的DispatcherServlet拦截“/”,拦截了所有的请求,同时对*.js,*.jpg ...
- 使用dom4j中SAXReader解析xml数据
public ApiConfig(String configFilePath) throws DocumentException{ SAXReader reader = new SAXReader() ...
- JavaScript 模拟 Dictionary
function Dictionary() { var items = {}; //判断是否包含Key值 this.has = function(key) { return key in items; ...
- JavaWeb & Tomcat
1 JavaWeb概述 Java在服务器端的应用有Servlet,JSP和第三方框架等. Java的Web框架基本都遵循特定的路数:使用Servlet或者Filter拦截请求,使用MVC的思想设计架构 ...
- VUE 全局变量的几种实现方式
最近在学习VUE.js 中间涉及到JS全局变量,与其说是VUE的全局变量,不如说是模块化JS开发的全局变量. 1.全局变量专用模块 就是以一个特定模块来组织管理这些全局量,需要引用的地方导入该模块便好 ...
- Python 总结
python3.7下载地址 Python安装pip 1.首先检查linux有没有安装python-pip包,直接执行 yum install python-pip 2.没有python-pip包就执行 ...