C++Primer Plus笔记——第四章 复合类型及课后编程练习答案
发布日期:2021-06-29 01:50:47 浏览次数:2 分类:技术文章

本文共 23550 字,大约阅读时间需要 78 分钟。

目录


本章小结  

    本章主要论述了数组、指针和引用。在C + +语言中,它们是相互交织在一起的,对其中一个概念的理解有助于对其他槪念的理解。

      数组是一个由若干相同类型数据组成的集合,数组中特定的元素通过下标来访问。数组可以具有一维到多维的多种类型,一维数组是最常见的,字符数组是最常使用的,它可以用来保存字符串。标准c++语言没有定义内置的字符串数据类型,而是将字符串作为字符数组来实现。 数组为创建相关变量的列表提供了一种便利的方法。数组由连续存储单元组成,它的起始地址对应于数组的第一个元素,数组名本身是数组的首地址,它使得数组作为函数参数来传递从空间 利用上显得更合理。
      在C++中,数组和指针有着密切的关系。指针是一个包含内存地址的对象,它不仅仅是地址,还与所指对象类型相关。通常,指针被用来访问另一个对象的值,这个另外的对象常常是一个数组,当程序把一个数组传递给函数时,C++实际上把数组第一个元素的地址传递给该函数3 通过递增指针的值,可以使指针直接指向数组的下一个元素。
      引用是C++独有的特性,引用实质上就是另一个变量的别名。
使用new和delete运算符可以进行动态存储分配。这样,程序就能在运行时指定所申请内存空间的大小。

 

程序清单

4.1 arrayone.cpp   使用数组

// arrayone.cpp -- small arrays of integers#include "stdafx.h"#include 
int main(){ using namespace std; int yams[3];    //creates array with three elements yams[0] = 7;    //assign value to first element yams[1] = 8; yams[2] = 6; int yamcosts[3] = {20,30,5};//create, initialize array //NOTE:if your C++ compiler or translator can't initialize this array,use static int yamcosts[3] instead of int yamcosts[3] cout << "Total yams = "; cout << yams[0] + yams[1] + yams[2] << endl; cout << "The package with " << yams[1] << " yams costs "; cout << yamcosts[1] << " cents per yam.\n"; int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1]; total = total + yams[2] * yamcosts[2]; cout << "The total yam expense is " << total << " cents.\n"; cout << "\nSize of yams array = " << sizeof yams; cout << " bytes.\n"; cout << "Size of one element = " << sizeof yams[0]; cout << " bytes.\n";    return 0;}

4.2  string.cpp   使用cstring

//string.cpp -- storing strings in an array#include "stdafx.h"#include 
#include
int main(){ using namespace std; const int Size = 15; char name1[Size];             //empty array char name2[Size] = "C++owboy";//initialized array //NOTE:some implementations may require the static keyword to initialize the array name2 cout << "Howdy! I'm " << name2 << "! What's your name?\n"; cin >> name1; cout << "well, " << name1 << ", your name has "; cout << strlen(name1) << " letters and is stored\n"; cout << "in an array of " << sizeof(name1) << " bytes \n"; cout << "Your initial is " << name1[0] << ".\n"; name2[3] = '\0';             //set to null character cout << "Here are the firsr 3 charaters of my name: "; cout << name2 << endl; return 0;}

4.3  instr1.cpp   字符串输入

//instr1.cpp -- reading more than one string#include "stdafx.h"#include 
int main(){ using namespace std; const int ArSize = 20; char name[ArSize]; char dessert[ArSize]; cout << "Enter your name:\n"; cin >> name; cout << "Enter your favorite dessert:\n"; cin >> dessert; cout << "I have some delicious " << dessert << " for you. " << name << ".\n"; return 0;}//输入时如果有空格,就相当于输入了两个数组,因为cin在识别输入时,是将字符串放到数组中,并自动在结尾添加空字符

4.4  instr2.cpp   使用cin.getline

//instr2.cpp -- reading more than one word with getline#include "stdafx.h"#include 
int main(){ using namespace std; const int ArSize = 20; char name[ArSize]; char dessert[ArSize]; cout << "Enter your name:\n"; cin.getline(name, ArSize);//reads through newline cout << "Enter your favorite dessert:\n"; cin.getline(dessert, ArSize); cout << "I have some delicious " << dessert; cout << " for you. " << name << " .\n"; return 0;}//getline()函数每次读取一行

4.5  instr3.cpp   拼接方式

//instr3.cpp -- reading more than one word with get() & get()#include "stdafx.h"#include 
int main(){ using namespace std; const int ArSize = 20; char name[ArSize]; char dessert[ArSize]; cout << "Enter your name:\n"; cin.get(name, ArSize).get();//reads string,newline cout << "Enter your favorite dessert:\n"; cin.get(dessert, ArSize).get(); cout << "I have some delicious " << dessert; cout << " for you. " << name << " .\n"; return 0;}

4.6   numstr.cpp  混合字符串和数字

//numstr.cpp -- following number input with line input#include "stdafx.h"#include 
int main(){ using namespace std; cout << "What year was your house built?\n"; int year; cin >> year; cout << "What is its street address?\n"; char address[80]; cin.getline(address, 80); cout << "Year built: " << year << endl; cout << "Address: " << address << endl; cout << "Done!\n"; return 0;}

4.7   strtype1.cpp  string类

//strtype1.cpp -- using the C++ string class#include "stdafx.h"#include 
#include
             //make string class availableint main(){ using namespace std; char charr1[20];           //create an empty array char charr2[20] = "jaguar";//create an initialized array string str1;               //create an empty string object 可以声明为简单变量而不是数组 string str2 = "panther";   //create an initialized string cout << "Enter a kind of feline: "; cin  >> charr1; cout << "Enter another kind of feline: "; cin  >> str1;              //use cin for input cout << "Here are some felines:\n"; cout << charr1 << " " << charr2 << "" << str1 << " " << str2 << endl;      //use cout for output cout << "The third letter in " << charr2 << " is " << charr2[2] << endl; cout << "The third letter in " << str2 << " is " << str2[2] << endl;   //use array notation return 0;}

4.8   strtype2.cpp  string类

//strtype2.cpp -- assigning,adding,and appending#include "stdafx.h"#include 
#include
//make string class availableint main(){ using namespace std; string s1 = "penguin"; string s2, s3; cout << "You can assign one string object to another: s2 = s1\n"; s2 = s1; cout << "s1: " << s1 << ", s2:" << s2 << endl; cout << "You can assign a C-style string to a string object.\n"; cout << "s2 = \"buzzard\"\n"; s2 = "buzzard"; cout << "s2: " << s2 << endl; cout << "You can concatenate strings: s3 = s1 + s2\n"; s3 = s1 + s2; cout << "s3: " << s3 << endl; cout << "You can append strings.\n"; s1 += s2; cout << "s1 += s2 yields s1 = " << s1 << endl; s2 += " for a day"; cout << "s2 += \"for a day\" yields s2 = " << s2 << endl; return 0;}

4.9   strtype3.cpp  string类

//strtype3.cpp -- more string class features#include "stdafx.h"#include 
#include
             //make string class available#include
            //C-style string libraryint main(){ using namespace std; char charr1[20];           //create an empty array char charr2[20] = "jaguar";//create an initialized array string str1;               //create an empty string object 可以声明为简单变量而不是数组 string str2 = "panther";   //create an initialized string //assignment for string objects and character arrays str1 = str2;               //copy str2 to str1  strcpy(charr1, charr2);    //copy charr2 to charr1 //appending for string objects and character arrays str1 += " paste";          //add paste to end of strl strcat(charr1, " juice");  //add juice to end of charr1 //finding the length of a string object and aC-style string int len1 = str1.size();    //obtain length of str1 int len2 = strlen(charr1); //obtain length of charr1 cout << "The string " << str1 << " contains " << len1 << " characters.\n"; cout << "The string " << charr1 << " contains " << len2 << " characters.\n"; return 0;}//strcpy和strcat函数可能会报错:error C4996: : This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.//解决方法:https://jingyan.baidu.com/article/ce436649fd61543773afd32e.html

4.10  strtype4.cpp   string类

//strtype4.cpp -- line input#include "stdafx.h"#include 
#include
             //make string class available#include
            //C-style string libraryint main(){ using namespace std; char charr[20]; string str; cout << "Length of string in charr before input: " << strlen(charr) << endl;//对于未被初始化的数据,第一个空字符的出现位置是随机的,因此得到的结果可能不同 cout << "Length of string in str before input: " << str.size() << endl; cout << "Enter a line of text:\n"; cin.getline(charr, 20); //indicate maximum length cout << "You entered: " << charr << endl; cout << "Enter another line of text:\n"; getline(cin, str);//cin now an argument ; no length specifier cout << "You entered: " << str << endl; cout << "Length of string in charr after input: " << strlen(charr) << endl; cout << "Length of string in str after input: " << str.size() << endl; return 0;}

4.11  structur.cpp  初始化结构

//structur.cpp -- a simple structure#include "stdafx.h"#include 
struct inflatable//structure declaration{ char name[20]; float volume; double price;};int main(){ using namespace std; inflatable guest = { "Glorious Gloria",//name value 1.88,// volume value 29.99//price value };//guest is a structure variable of type inflatable //It's initialized to the indicated values inflatable pal = { "Audacious Arthur", 3.12, 32.99 }; //pal is a second variable of type inflatable //NOTE:some implementations require using //static inflatable guest = cout << "Expand your guest list with " << guest.name; cout << " and " << pal.name << "!\n";//pal.name is the name member of the pal variable cout << "You can have both for $"; cout << guest.price + pal.price << "!\n"; return 0;}

4.12   assgn_st.cpp   结构赋值

//assgn_st.cpp--assigning structures#include "stdafx.h"#include 
struct inflatable{ char name[20]; float volume; double price;};int main(){ using namespace std; inflatable bouquet = { "sunflowers", 0.20, 12.49 };//注意加分号 inflatable choice; cout << "bouquet: " << bouquet.name << " for $"; cout << bouquet.price << endl; choice = bouquet; cout << "choice: " << choice.name << " for $"; cout << choice.price << endl; return 0;};

4.13   arrstruc.cpp   结构数组

//arrstruc.cpp -- an array of structures#include "stdafx.h"#include 
struct inflatable{ char name[20]; float volume; double price;};int main(){ using namespace std; inflatable guests[2]= { {"Bambi",0.5,21.99},   {"Godzilla",2000,565.99} }; cout << "The guests " << guests[0].name << " and " << guests[1].name << "\nhave a combined volume of " << guests[0].volume + guests[1].volume << " cubic feet.\n"; return 0;}

4.14    address.cpp   &运算符的用法

//address.cpp -- using the & operator to find address#include "stdafx.h"#include 
int main(){ using namespace std; int donuts = 6; double cups = 4.5; cout << "donuts value = " << donuts; cout << " and donuts address = " << &donuts << endl; //NOTE:you may need to use unsigned (&donuts) and unsigned (&cups) cout << "cups value = " << cups; cout << " and cups address = " << &cups << endl; return 0;}

4.15    pointer.cpp   声明指针

//pointer.cpp -- our first pointer variable#include "stdafx.h"#include 
int main(){ using namespace std; int updates = 6;//declare a variable int * p_updates;//declare pointer to an int p_updates = &updates;//assign address of int to pointer //express values two ways cout << "Values: updates = " << updates; cout << " , p_updates = " << *p_updates << endl; //express address two ways cout << "Addresses: &updates = " << &updates; cout << ", p_updates = " << p_updates << endl; //use pointer to change value *p_updates = *p_updates + 1; cout << "Now updates = " << updates << endl; return 0;}

4.16   init_ptr.cpp  将指针初始化为一个地址

//init_ptr.cpp -- initialize a pointer#include "stdafx.h"#include 
int main(){ using namespace std; int higgens = 5; int * pt = &higgens; cout << "Value of higgens = " << higgens << "; Address of higgens = " << &higgens << endl; cout << "Value of *pt = " << *pt<< "; Value of pt = " << pt << endl; return 0;}

4.17   use_new.cpp   new用于两种不同类型

//use_new.cpp -- using the new operator#include "stdafx.h"#include 
int main(){ using namespace std; int nights = 1001; int * pt = new int; *pt = 1001; cout << "night value = "; cout << nights << ": location " << &nights << endl; cout << "int "; cout << "value = " << *pt << ": location = " << pt << endl; double * pd = new double; *pd = 10000001.0; cout << "double "; cout << "value = " << *pd << ": location = " << pd << endl; cout << "location of pointer pd: " << &pd << endl; cout << "size of pt = " << sizeof(pt); cout << "size of *pt = " << sizeof(*pt) << endl; cout << "size of pd = " << sizeof(pd);  cout << "size of *pd = " << sizeof(*pd) << endl; return 0;}

4.18   arraynew.cpp  用new创建动态数组

//arraynew.cpp -- using the new operator for arrays#include "stdafx.h"#include 
int main(){ using namespace std; double *p3 = new double[3]; p3[0] = 0.2; p3[1] = 0.5; p3[2] = 0.8; cout << "p3[1] is " << p3[1] << ".\n"; p3 = p3 + 1; cout << "Now p3[0] is " << p3[0] << " and "; cout << "p3[1] is " << p3[1] << ".\n"; p3 = p3 - 1; delete[] p3; return 0;}

4.19  addpntrs.cpp   指针算数

//addpntrs.cppp -- pointer addition#include "stdafx.h"#include 
int main(){ using namespace std; double wages[3] = { 10000.0, 20000.0, 30000.0 }; short stacks[3] = { 3,2,1 }; //Here are two ways to get the address of an array double * pw = wages; //name of an array = address short * ps = &stacks[0];//or use address operator //with array element cout << "pw = " << pw << ", *pw = " << *pw << endl; pw = pw + 1; cout << "add 1 to the pw pointer : \n"; cout << "pw = " << pw << ", *pw = " << *pw << "\n\n"; cout << "ps = " << ps << ", *ps = " << *ps << endl; ps = ps + 1; cout << "add 1 to the ps pointer:\n"; cout << "ps = " << ps << ", *ps = " << *ps << "\n\n"; cout << "access two element with array notation\n"; cout << "stacks[0] = " << stacks[0] << "stack[1] = " << stacks[1] << endl; cout << "access two element with pointer notation\n"; cout << "*stacks = " << *stacks << ", *{stacks + 1} = " << *(stacks + 1) << endl; cout << sizeof(wages) << " = size of wages array\n"; cout << sizeof(pw) << " size of pw pointer\n"; return 0;}

4.20   ptrstr.cpp   使用不同形式的字符串

//ptrstr.cpp -- using pointers to strings#include "stdafx.h"#include 
#include
                   //declare strlen(),strcpy()int main(){ using namespace std; char animal[20] = "bear";         //animal holds bear const char * bird = "wren";       //bird holds address of string char * ps;                        //uninitialized cout << animal << " and ";        //display bear cout << bird << "\n";             //display wren // cout << ps << "\n";//may display garbage, may cause a crash cout << "Enter a kind of animal: "; cin >> animal;                    //ok if input < chars // cin >> ps ;Too horrible a blunder to try; ps doesn't point to allocated space ps = animal;                      //set ps to point to string cout << ps << "!\n";              //ok, same as using animal cout << "Before using strcpy():\n"; cout << animal << " at " << (int *)animal << endl; cout << ps << " at " << (int *)ps << endl; ps = new char[strlen(animal) + 1];//get new storage strcpy(ps, animal);               //copy string to new storage cout << "After using strcpy():\n"; cout << animal << " at " << (int *)animal << endl; cout << ps << " at " << (int *)ps << endl; delete[] ps; return 0;}

4.21  newstrct.cpp  访问指针成员

//newstrct.cpp -- using new with a structure#include "stdafx.h"#include 
struct inflatable // structure definition{ char name[20]; float volume; double price;};int main(){ using namespace std; inflatable * ps = new inflatable; // allot memory for structure cout << "Enter name of inflatable item: "; cin.get(ps->name, 20); // method 1 for member access cout << "Enter volume in cubic feet: "; cin >> (*ps).volume;//method 2 for member access cout << "Enter price : $"; cin >> ps->price; cout << "Name: " << (*ps).name << endl; //method 2 cout << "Volume: " << ps->volume << " cubic feet\n";//method 1 cout << "Price: $" << ps->price << endl; //method 1 delete ps; //free memory used by structure return 0;}

4.22   delete.cpp   演示delete

//delete.cpp -- using the delete operator#include "stdafx.h"#include 
#include
//or string.husing namespace std;char * getname(void);//function prototypeint main(){ char *name;//create pointer but no storage name = getname();//assign address of string to name cout << name << " at " << (int *)name << "\n"; delete[] name; // memory freed name = getname(); //reuse freed mamory cout << name << " at " << (int *)name << "\n"; delete[] name; // memory freed again return 0;}char * getname() // return pointer  to new string{ char temp[80]; //temporay storage cout << "Enter last name: "; cin >> temp; char * pn = new char[strlen(temp) + 1]; strcpy(pn, temp); //copy string into smaller space return pn; //temp lost when function ends}

4.23  mixtypes.cpp  类型组合

//mixtype.cpp -- some type combinations#include "stdafx.h"#include 
struct antarctica_years_end{ int year; /*some relly interesting data,etc.*/};int main(){ antarctica_years_end s01, s02, s03; s01.year = 1998; antarctica_years_end *pa = &s02; pa->year = 1999; antarctica_years_end trio[3];//array of structures trio[0].year = 2003;    std :: cout << trio->year << std::endl; const antarctica_years_end * arp[3] = { &s01,&s02,&s03 }; std::cout << arp[1]->year << std::endl; const antarctica_years_end **ppa = arp; auto ppb = arp;//C++11 automatic type deduction or else use const antarctica_years_end **ppb = arp; std::cout << (*ppa)->year << std::endl; std::cout << (*(ppb + 1))->year << std::endl; return 0;}

4.24   choices.cpp  vector对象
 

 //choices.cpp -- array variations#include "stdafx.h"#include 
#include
//STL C++98#include
//C+11int main(){ using namespace std; //C,original C++ double a1[4] = { 1.2,2.4,3.6,4.8 }; //C++98 STL vector
a2(4);//create vector with 4 element //no simple way to initialize in C98 a2[0] = 1.0 / 3.0; a2[1] = 1.0 / 5.0; a2[2] = 1.0 / 7.0; a2[3] = 1.0 / 9.0; //C++ -- create and initialize array object array
a3 = { 3.14,2.72,1.62,1.41 }; array
a4; a4 = a3;//valid for array object of same size //use array notation cout << "a1[2]: " << a1[2] << " at " << &a1[2] << endl; cout << "a2[2]: " << a2[2] << " at " << &a2[2] << endl; cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl; cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl; //misdeed a1[-2] = 20.2; cout << "a1[-2]: " << a1[-2] << " at " << &a1[-2] << endl; cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl; cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl; return 0;}

课后编程习题答案

//problem.cpp -- homework#include "stdafx.h"#include 
#include
#include
using namespace std;//problem_1struct student{ char fn[20]; char ln[20]; char grade; int age;};void display(student);int main(){ cout << "what is your first name?" << endl; student bs; cin.getline(bs.fn, asize); cout << "what is your last name?" << endl; cin.getline(bs.ln, asize); cout << "what letter grade do you deserve?" << endl; cin >> bs.grade; cout << "what is your age?" << endl; cin >> bs.age; display(bs); return 0;}void display(student name){ cout << "Name: " << name.fn << "," << name.ln << endl; cout << "Grade: " << char(name.grade + 1) << endl; cout << "Age: " << name.age << endl;}//problem2int main(){ string name, dessert; cout << "Enter your name: \n"; getline(cin, name); cout << "Enter your favorite dessert: \n"; getline(cin, dessert); cout << "I have some delicious " << dessert; cout << " for you, " << name << ".\n"; return 0;}//problem3int main(){ char fname[20]; char lname[20]; char fullname[2 * 20 + 1]; cout << "Enter your first name:";//输入名字,存储在fname[]数组中 cin.getline(fname, 20); cout << "Enter your last name:";//输入姓,存储在lname[]数组中 cin.getline(lname, 20); strncpy(fullname, lname, 20);//把姓lname 复制到fullname 空数组中 strcat(fullname, ", ");//把“, ”附加到上述fullname 尾部 strncat(fullname, fname, 20);//把fname 名字附加到上述fullname 尾部 fullname[2 * 20] = '\0';//为防止字符型数组溢出,在数组结尾添加结束符 cout << "Here's the information in a single string:" << fullname << endl;//显示组合结果 return 0;}//problem4int main(){ string fname, lname, attach, fullname; cout << "Enter your first name:"; getline(cin, fname);//note:将一行输入读取到string 类对象中使用的是getline(cin,str),它没有使用句点表示法,所以不是类方法 cout << "Enter your last name:"; getline(cin, lname); attach = ", "; fullname = lname + attach + fname; cout << "Here's the information in a single string:" << fullname << endl; return 0;}//problem5struct CandyBar{ char brand[20]; double weight; int calory;};int main(){ CandyBar snack = { "Mocha Munch",2.3,350 }; cout << "Here's the information of snack:\n"; cout << "brand:" << snack.brand << endl; cout << "weight:" << snack.weight << endl; cout << "calory:" << snack.calory << endl; return 0;}//problem6struct CandyBar{ char brand[20]; double weight; int calory;};int main(){ using namespace std; CandyBar snack[3] = { { "Mocha Munch",2.3,350 }, { "XuFuJi",1.1,300 }, { "Alps",0.4,100 } }; for (int i = 0; i < 3; i++)//利用for 循环来显示snack 变量的内容 { cout << snack[i].brand << endl << snack[i].weight << endl << snack[i].calory << endl << endl; } return 0;}//problem7struct pizza{ char company[20]; double diameter; double weight;};int main(){ using namespace std; pizza pie;//创建一个名为pie 的结构变量 cout << "What's the name of pizza company:"; cin.getline(pie.company, 20); cout << "What's the diameter of pizza:"; cin >> pie.diameter; cout << "What's the weight of pizza:"; cin >> pie.weight; cout << "company:" << pie.company << endl; cout << "diameter:" << pie.diameter << " cm" << endl; cout << "weight:" << pie.weight << " g" << endl; return 0;}//problem8struct pizza//声明结构{ char company[20]; double diameter; double weight;};int main(){ using namespace std; pizza *pie = new pizza;//使用new 创建动态结构 cout << "What's the diameter of pizza:"; cin >> pie->diameter; cin.get();//读取下一个字符 cout << "What's the name of pizza company:"; cin.get(pie->company, 20); cout << "What's the weight of pizza:"; cin >> pie->weight; cout << "company:" << pie->company << endl; cout << "diameter:" << pie->diameter << " cm" << endl; cout << "weight:" << pie->weight << " g" << endl; delete pie;//delete 释放内存 return 0;}//problem9struct CandyBar{ string brand; double weight; int calory;};int main(){ CandyBar *snack = new CandyBar[3]; snack[0].brand = "A";//单个初始化由new 动态分配的内存 snack[0].weight = 1.1; snack[0].calory = 200; snack[1].brand = "B"; snack[1].weight = 2.2; snack[1].calory = 400; snack[2].brand = "C"; snack[2].weight = 4.4; snack[2].calory = 500; for (int i = 0; i < 3; i++) { cout << " brand: " << snack[i].brand << endl; cout << " weight: " << snack[i].weight << endl; cout << " calorie: " << snack[i].calory << endl << endl; } delete[] snack; return 0;}//problem10int main(){ const int Size = 3; int success[Size]; cout << "Enter your success of the three times 40 meters running:\n"; cin >> success[0] >> success[1] >> success[2]; cout << "success1:" << success[0] << endl; cout << "success2:" << success[1] << endl; cout << "success3:" << success[2] << endl; double average = (success[0] + success[1] + success[2]) / 3; cout << "average:" << average << endl; return 0;}

 

转载地址:https://blog.csdn.net/yukinoai/article/details/79761556 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:C++Primer Plus笔记——第五章 循环及关系表达式及课后编程练习答案
下一篇:C++Primer Plus笔记——第三章 处理数据及课后编程练习答案

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月05日 06时06分00秒