[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). 只有初始化时可以用“=”,其它时候均不可以给数组直接赋值,除了赋值的元素以外 ...
随机推荐
- 13.vue组件
vue组件(一) 组件嵌套: 1.全局嵌套: <!doctype html> <html> <head> <meta charset="utf-8& ...
- Python学习之旅(三十三)
Python基础知识(32):网络编程(Ⅰ) 网络通信是两台计算机上的两个进程之间的通信,而网络编程就是如何在程序中实现两台计算机的通信 P协议负责把数据从一台计算机通过网络发送到另一台计算机 TCP ...
- 使用正则表达式进行某网页中的email邮箱抽取
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; impo ...
- Nginx负载均衡后端健康检查
参考文档:https://www.cnblogs.com/kevingrace/p/6685698.html 本次使用第三方模块nginx_upstream_check_module的,要使用这个第三 ...
- arcpy加载mxd文件时,无效的MXD路径,提示assert (os.path.isfile(mxd) or (mxd.lower() == "current")), gp.getIDMessage(89004, "Invalid MXD filename")
无效的MXD路径,将路径前加‘u’,改为这种: mxdPath = u"C:\\1331\\DB\\Original Files\\dd.mxd" 参考: https://gis. ...
- iOS 微信打开第三方应用(Universal Links 和 URL Schemes)
一.前言 项目中时常有这种需求, 是通过链接跳转到应用内部,现在iOS主流的方案有两个 Schema: 常用在于一个应用跳转到另一个应用内部,属于应用间的跳转.当然ios9以下,网页可以通过schem ...
- Docker入门基础(一)
Docker入门基础 Linux只存在文件目录,不存在“盘”的概念 Dockers优点:方便部署环境.资源占用少(微服务) Docker的三大概念 镜像:类似虚拟机的镜像.用俗话说就是安装文件.容器: ...
- http 你造吗?
HTTP是一个属于应用层的面向对象的协议,由于其简捷.快速的方式,适用于分布式超媒体信息系统.它于1990年提出,经过几年的使用与发展,得到不断地完善和扩展.目前在WWW中使用的是HTTP/1.0的第 ...
- 2、jeecg 笔记之 t:dictSelect 或 t:dgCol 自定义字典
1.需求 先说一下需求场景吧,我们知道 jeecg 中提供了下拉,其中包含两种使用场景: 一种是直接通过 t:dictSelect 使用,再就是 t:dgCol 用于表头的列表工具条标签: 总之就是 ...
- 只需十四步:从零开始掌握 Python 机器学习(附资源)
分享一篇来自机器之心的文章.关于机器学习的起步,讲的还是很清楚的.原文链接在:只需十四步:从零开始掌握Python机器学习(附资源) Python 可以说是现在最流行的机器学习语言,而且你也能在网上找 ...