1.为复习题5描述的类提供方法定义,并编写一个小程序来演示所有的特性。
复习题5:定义一个类来表示银行帐户。数据成员包括储户姓名、账号(使用字符串)和存款。成员函数执行如下操作:
● 创建一个对象并将其初始化;
● 显示储户姓名、账号和存款;
● 存入参数指定的存款;
● 取出参数指定的款项。

//bank.h:定义类成员及函数
#ifndef BANK_H_
#define BANK_H_#include <string>
using namespace std;class BankAccount
{public:BankAccount();//默认构造函数BankAccount(const char* str, string id, int ban);//自定义的重载构造函数~BankAccount();//析构函数void showinfo() const;void deposit(const int num1);void withdraw(const int num2);
private:string name;string id;double banlance;
};
#endif // !BANK_H_
//bank.cpp:定义类中的函数
#include <iostream>
#include "bank.h"BankAccount::BankAccount()
{name = "Unknown user";id = "00000000000";banlance = 0;
}
BankAccount::BankAccount(const char* str,string acc,int ban)
{name = str;banlance = ban;id = acc;
}BankAccount::~BankAccount()
{}void BankAccount::showinfo() const
{cout << "The infomation below is about the account:\n";cout << "User: " << name << endl;cout << "ID: " << id << endl;cout << "Banlance: " << banlance << endl;
}void BankAccount::deposit(const int num1)
{if (num1 > 0){banlance += num1;cout << "Deposit " << num1 << " yuan.\n";}elsecout << "Negative numbers are not allowed.\n";
}void BankAccount::withdraw(const int num2)
{if (num2 > banlance)cout << "Cannot be greater than balance.\n";else if (num2<banlance && num2 > 0){banlance -= num2;cout << "Withdraw " << num2<< " yuan.\n";}elsecout << "Negative numbers are not allowed.\n";
}
/* *************************************************
* 文件名:
* 创建人:px
* 创建时间:2020/4/5
* 描述:演示程序
************************************************* */
#include <iostream>
#include "bank.h"int main()
{BankAccount pep1;BankAccount pep2=BankAccount("px","12345677888" ,200);pep1.showinfo();pep2.showinfo();pep2.deposit(500);pep2.withdraw(200);pep2.showinfo();return 0;
}

2.下面是一个非常简单的类定义:

#include <string>
using namespace std;
class Person
{public:Person() { lname = "";fname [0]= '\0'; };Person(const string& ln, const char* fn = "Heyyou");~Person();void Show() const;void Formashow() const;
private:static const int LIMIT = 25;string lname;char fname[LIMIT];
};

它使用了一个string对象和一个字符数组,让您能够比较它们的用法。请提供未定义的方法的代码,以完成这个类的实现。再编写一个使用这个类的程序,它使用了三种可能的构造函数调用(没有参数、一个参数和两个参数)以及两种显示方法。下面是一个使用这些构造函数和方法的例子:

int main()
{Person one;Person two("Smythecraft");Person three("Dimwiddy", "Sam");one.Show();cout << endl;one.Formashow();
}
//person.h
#ifndef PERSON_H_
#define PERSON_H_#include <string>
using namespace std;
class Person
{public:Person() { lname = "";fname [0]= '\0'; };Person(const string& ln, const char* fn = "Heyyou");~Person();void Show() const;void Formashow() const;
private:static const int LIMIT = 25;string lname;char fname[LIMIT];
};
#endif // !PERSON_H_
//person.cpp
#include <iostream>
#include <cstring>
#include "person.h"Person::Person(const string& ln, const char* fn)
{lname = ln;int count = 0;strcpy_s(fname, fn);
}Person::~Person()
{}void Person::Show() const
{cout << "Name(firstname lastname format): " << fname << " "<<lname << endl;
}void Person::Formashow() const
{cout << "Name(lastname,firstname format): " << lname << "," << fname << endl;
}
//main.cpp/* *************************************************
* 文件名:
* 创建人:px
* 创建时间:2020/4/5
* 描述:
************************************************* */
#include <iostream>
#include "person.h"int main()
{Person one;Person two("Smythecraft");Person three("Dimwiddy", "Sam");one.Show();cout << endl;one.Formashow();two.Show();cout << endl;two.Formashow();three.Show();cout << endl;three.Formashow();return 0;
}

3.完成第9章的编程练习1,但要用正确的golf类声明替换那里的代码。用带合适参数的构造函数替换setgolf(golf &, const char , int),以提供初始值。保留setgolf( )的交互版本,但要用构造函数来实现它(例如,setgolf( )的代码应该获得数据,将数据传递给构造函数来创建一个临时对象,并将其赋给调用对象,即this)。
第9章编程练习1代码如下:
golf.h文件:负责声明常量、结构定义、函数声明。

//golf.h
const int Len = 40;
struct golf
{char fullname[Len];int handicap;
};
void setgolf(golf& g, const char* name, int hc);//无交互版本
int setgolf(golf& g);//有交互版本
void handicap(golf& g, int hc);//设置handicap新值
void showgolf(const golf& g);//显示golf结构的内容

golf.cpp文件:负责函数原型。

//golf.cpp
#include <iostream>
#include <string>
#include <cstring>
#include "golf.h"void setgolf(golf& g, const char* name, int hc)
{strcpy_s(g.fullname, name);g.handicap = hc;
}
int setgolf(golf& g)
{using namespace std;cout << "Enter full name.\n";cin.getline(g.fullname,Len);cout << "Enter handicap.\n";cin >> g.handicap;cin.get();//清除输入流中的结束符号,防止给下次循环造成 干扰if ((g.fullname != '\0') && (g.handicap != 0))return 1;elsereturn 0;
}
void handicap(golf& g, int hc)
{g.handicap = hc;
}
void showgolf(const golf& g)
{using namespace std;cout << "Full name: " << g.fullname<<endl;cout << "Handicap: " << g.handicap<<endl;
}

main.cpp文件:负责程序运行逻辑。

/* *************************************************
* 文件名:
* 创建人:px
* 创建时间:2020/3/27
* 描述:
************************************************* */
#include <iostream>
#include <string>
#include "golf.h"
int main()
{using namespace std;const int num = 3;golf inter[num];golf noninter[num];setgolf(noninter[0], "A BC", 12);setgolf(noninter[1], "B BA", 13);setgolf(noninter[2], "C CA", 13);for (int i = 0;i < num;i++)showgolf(noninter[i]);for (int i = 0;i < num;i++){setgolf(inter[i]);showgolf(inter[i]);}return 0;
}

改用类的方法:

//class.h
#ifndef CLASS_H_
#define CLASS_H_#include <string>
#include <iostream>
using namespace std;class Golf
{public:Golf();                                  //默认构造函数,有交互版本Golf(const char* str,const int hc);        //重载的构造函数,无交互版本,直接按照给定值设定对象~Golf() {};void sethandicap(int hc);               //设置handicap新值void showgolf() const;                    //显示golf结构的内容
private:static const int LEN = 40;char fullname[LEN];int handicap;
};
#endif // !CLASS_H_
//class.cpp
#include "class.h"
#include <iostream>
using namespace std;Golf::Golf()
{//方式一:按题目要求使用 *this//char tempname[LEN];//int temphandicap = 0;//cout << "Enter full name:\n";//cin.getline(tempname, LEN);//cout << "Enter handicap.\n";//cin >> temphandicap;//cin.get();                              //去除上一步中留在输入流中的换行符//*this = Golf(tempname, temphandicap);      //调用默认重载函数,返回自己//方式二:cout << "Enter full name:\n";cin.getline(fullname, LEN);cout << "Enter handicap.\n";cin >> handicap;cin.get();                                 //去除上一步中留在输入流中的换行符
}Golf::Golf(const char* str, const int hc)
{strcpy_s(fullname, str);handicap = hc;
}void Golf::sethandicap(int hc)
{handicap = hc;
}void Golf::showgolf() const
{cout << "Full name: " << fullname << endl;cout << "Handicap: " << handicap << endl;
}
//main.cpp
/* *************************************************
* 文件名:
* 创建人:px
* 创建时间:2020/4/5
* 描述:
************************************************* */
#include <iostream>
#include "class.h"int main()
{using namespace std;Golf inter("px",2);Golf noninter;inter.showgolf();inter.sethandicap(5);inter.showgolf();noninter.showgolf();noninter.sethandicap(8);noninter.showgolf();return 0;
}

4.完成第9章的编程练习4,但将Sales结构及相关的函数转换为一个类及其方法。用构造函数替换setSales(sales &,double [ ],int)函数。用构造函数实现setSales(Sales &)方法的交互版本。将类保留在名称空间SALES中。

//clss.h
#ifndef CLASS_H_
#define CLASS_H_#include <string>
#include <iostream>class Sales
{public:Sales();                         //有交互版本Sales(const double ar[], int n); //无交互版本~Sales() {};void showSales() const;
private:enum { QUARTER = 4 };double sales[QUARTER];double average;double max;double min;
};
#endif // !CLASS_H_
//clss.cpp
#include "class.h"
#include <iostream>
using namespace std;Sales::Sales()
{double total = 0.0;cout << "Enter 4 sales\n";for (int i = 0;i < QUARTER;i++)cin >> sales[i];max = sales[0];min = sales[0];for (int i = 0;i < QUARTER;i++){total += sales[i];if (max < sales[i])max = sales[i];if (min > sales[i])min = sales[i];}average = total / QUARTER;
}Sales::Sales(const double ar[], int n)
{int num = n > QUARTER ? QUARTER : n;double total = 0.0;max = ar[0];min = ar[0];for (int i = 0;i < num;i++){sales[i] = ar[i];total += ar[i];if (max < ar[i])max = ar[i];if (min > ar[i])min = ar[i];}average = total / num;
}void Sales::showSales() const
{cout << "Show sale's information:\n";cout << "Average:\n";cout << average << endl;cout << "Max:\n";cout << max << endl;cout << "Min:\n";cout << min << endl;
}
//main.cpp
/* *************************************************
* 文件名:
* 创建人:px
* 创建时间:2020/4/10
* 描述:
************************************************* */
#include <iostream>
#include "class.h"int main()
{using namespace std;const double num[4] = { 12.3,12.4,34.2,15 };Sales sale1;          Sales sale2=Sales(num,4);          sale1.showSales();sale2.showSales();return 0;
}

5.考虑下面的结构声明:

struct customer
{char fullname[35];double payment;
};

编写一个程序,它从栈中添加和删除customer结构(栈用Stack类声明表示)。每次customer结构被删除时,其payment的值都被加入到总数中,并报告总数。注意:应该可以直接使用Stack类而不作修改;只需修改typedef声明,使Item的类型为customer,而不是unsigned long即可。

//clss.h
#ifndef CLASS_H_
#define CLASS_H_#include <string>
#include <iostream>
struct customer
{char fullname[35];double payment;
};
typedef customer Item;class Stack
{public:Stack();~Stack() {};bool isempty() const;bool isfull() const;bool push(const Item& item);    //入栈bool pop(Item& item);       //出栈
private:enum{ MAX = 10 };      //栈深度Item items[MAX];       //数组盛放栈元素int top;               //记录栈的长度double total;           //设立一个记录总数的值
};#endif // !CLASS_H_
//class.cpp
#include "class.h"Stack::Stack()
{total = 0.0;top = 0; //创建新的栈是,栈长度清0
}bool Stack::isempty() const
{return top==0;
}bool Stack::isfull() const
{return top==MAX;
}bool Stack::push(const Item& item)
{using namespace std;cout << item.fullname << " push.\n";if (top < MAX){items[top++] = item;return true;}elsereturn false;
}bool Stack::pop(Item& item)
{using namespace std;if (top > 0){item = items[--top];total += item.payment;                      cout << "Total: " << total << endl;         //计数total值return true;}elsereturn false;
}
//main.cpp
/* *************************************************
* 文件名:
* 创建人:px
* 创建时间:2020/4/10
* 描述:
************************************************* */
#include <iostream>
#include "class.h"
int main()
{double tot=0;using namespace std;customer cus1 = { "A",20 };customer cus2 = { "B",40 };Stack cusstack;                  //创建新的栈,记录customer的变化cusstack.push(cus1);            //cus1入栈cusstack.push(cus2);            //cus2入栈cusstack.pop(cus2);             //cus2出栈,栈的原则是先入后出,这里将cus1和cus2的顺序颠倒也仍旧按照先入后出的原则执行。cusstack.pop(cus1);                //cus1出栈return 0;
}

6.下面是一个类声明:

#ifndef CLASS_H_
#define CLASS_H_#include <string>
#include <iostream>
class Move
{public:Move(double a = 0, double b = 0);~Move() {};void showmove() const;Move add(const Move& m) const;void reset(double a = 0, double b = 0);
private:double x;double y;
};

请提供成员函数的定义和测试这个类的程序。

//clss.h
#ifndef CLASS_H_
#define CLASS_H_#include <string>
#include <iostream>
class Move
{public:Move(double a = 0, double b = 0);~Move() {};void showmove() const;Move add(const Move& m) const;void reset(double a = 0, double b = 0);
private:double x;double y;
};
#endif // !CLASS_H_
#include "class.h"Move::Move(double a, double b)
{x = a;y = b;
}void Move::showmove() const
{using namespace std;cout << "x: " << x << endl;cout << "y: " << y << endl;
}Move Move::add(const Move& m) const
{Move temp;temp.x = m.x + this->x;temp.y = m.y + this->y;return temp;
}void Move::reset(double a, double b)
{x = a;y = b;
}
//main.cpp
/* *************************************************
* 文件名:
* 创建人:px
* 创建时间:2020/4/10
* 描述:
************************************************* */
#include <iostream>
#include "class.h"int main()
{using namespace std;Move p1;Move p2(10, 20);Move p3(20, 20);p1.showmove();p2.showmove();p3.showmove();p3=p3.add(p2);      //将返回的结构重新赋值给p3p3.showmove();p3.reset();p3.showmove();return 0;
}

7.Betelgeusean plorg有这些特征。
数据:
● plorg的名称不超过19个字符;
● plorg有满意指数(CI),这是一个整数。
操作:
● 新的plorg将有名称,其CI值为50;
● plorg的CI可以修改;
● plorg可以报告其名称和CI;
● plorg的默认名称为“Plorga”。
请编写一个Plorg类声明(包括数据成员和成员函数原型)来表示plorg,并编写成员函数的函数定义。然后编写一个小程序,以演示Plorg类的所有特性。

//clss.h
#ifndef CLASS_H_
#define CLASS_H_#include <string>
#include <iostream>
class Plorg
{public:Plorg(const char* ar="Plorga",int ci=50);~Plorg() {};void setCI(int n);void showPlorg() const;
private:char fullname[20];int CI;
};
#endif // !CLASS_H_
#include "class.h"Plorg::Plorg(const char* ar, int ci)
{strcpy_s(fullname, ar);CI = ci;
}void Plorg::setCI(int n)
{CI = n;
}void Plorg::showPlorg() const
{using namespace std;cout << "Name :" << fullname << endl;cout << "CI: " << CI << endl;
}
//main.cpp
/* *************************************************
* 文件名:
* 创建人:px
* 创建时间:2020/4/10
* 描述:
************************************************* */
#include <iostream>
#include "class.h"
int main()
{Plorg p1;Plorg p2("A", 40);p1.showPlorg();p2.showPlorg();p2.setCI(20);p2.showPlorg();return 0;
}

8.可以将简单列表描述成下面这样:
● 可存储0或多个某种类型的列表;
● 可创建空列表;
● 可在列表中添加数据项;
● 可确定列表是否为空;
● 可确定列表是否为满;
● 可访问列表中的每一个数据项,并对它执行某种操作。
可以看到,这个列表确实很简单,例如,它不允许插入或删除数据项。
请设计一个List类来表示这种抽象类型。您应提供头文件list.h和实现文件list.cpp,前者包含类定义,后者包含类方法的实现。您还应创建一个简短的程序来使用这个类。该列表的规范很简单,这主要旨在简化这个编程练习。可以选择使用数组或链表来实现该列表,但公有接口不应依赖于所做的选择。也就是说,公有接口不应有数组索引、节点指针等。应使用通用概念来表达创建列表、在列表中添加数据项等操作。对于访问数据项以及执行操作,通常应使用将函数指针作为参数的函数来处理:

void visit(void (*pf)(Item&));

其中,pf指向一个将Item引用作为参数的函数(不是成员函数),Item是列表中数据项的类型。visit( )函数将该函数用于列表中的每个数据项。

//clss.h
#ifndef CLASS_H_
#define CLASS_H_#include <string>
#include <iostream>
typedef double Item;        //创建 double 类型的列表
class List
{public:List();~List() {};bool add(Item& n);bool isempty();bool isfull();void visit(void (*pf)(Item& temp));
private:enum { MAX = 10 };int length;Item items[MAX];      //用数组来完成列表
};
void total(Item& temp);     //定义操作函数#endif // !CLASS_H_
#include "class.h"List::List()
{length = 0;
}bool List::add(Item& n)
{if (length < MAX){items[length++] = n;return true;}else return false;
}bool List::isempty()
{return length == 0;
}bool List::isfull()
{return length==MAX;
}void List::visit(void(*pf)(Item& temp))
{for (int i = 0;i < length;i++){pf(items[i]);}
}void total(Item& temp)
{using namespace std;static  double total = 0.0;total += temp;cout << "Total: " << total << endl;
}
//main.cpp
/* *************************************************
* 文件名:
* 创建人:px
* 创建时间:2020/4/10
* 描述:
************************************************* */
#include <iostream>
#include "class.h"int main()
{double a = 12, b = 34;List dlist;dlist.add(a);dlist.add(b);dlist.visit(total);return 0;
}

C++ Primer Plus (第六版)编程练习记录(chapter10 对象和类)相关推荐

  1. C Primer Plus 第六版编程练习第五章答案

    1,编写一个程序,把用分钟表示的时间转换成用小时和分钟表示的时间.使用#define或const创建一个表示60的符号常量或const变量.通过while循环让用户重复输入值,直到用户输入小于或等于0 ...

  2. C++ Primer Plus 第六版编程练习——第6章

    ★★★★★备注★★★★★ 使用的编译环境为 Visual Studio 2017 默认省略了如下内容: #include "stdafx.h"                    ...

  3. C Primer Plus 第六版---编程练习2

    1.编写一个程序,调用一次 printf()函数,把你的姓名打印在一行.再调用一次 printf()函数,把你的姓名分别打印在两行.然后,再调用两次printf()函数,把你的姓名打印在一行.输出应如 ...

  4. C Primer Plus 第六版---编程练习4

    1.编写一个程序,提示用户输入名和姓,然后以"名,姓"的格式打印出来. /*输入名和姓打印"名,姓" */ #include<stdio.h> #d ...

  5. C Primer Plus 第六版编程练习第七章答案

    1,编写一个程序读取输入,读到#字符停止,然后报告读取空格数,换行符数目以及所有的其它字符数目. /*7.12*/ #include<stdio.h> #define STOP '#' # ...

  6. C Primer Plus 第六版 编程练习第四章答案 最新出炉

    文章目录 1,编写一个程序,提示用户输入名和姓,然后以"名,姓"的格式打印出来. 2,编写一个程序,提示用户输入名字,并执行以下操作: 3,编写一个程序,读取一个浮点数,首先以小数 ...

  7. C++ Primer Plus第六版第六章编程练习 第4题, 加入Benevolent Order of Programmer后,在BOP大会上

    /*************************************************************************************************** ...

  8. C++ Primer Plus 第六版 所有章节课后编程练习答案

    我的独立博客地址:www.blog4jimmy.com,欢迎大家关注 下面的是C++ Primer Plus 第六版所有章节的课后编程练习的答案,都是博主自己写的,有不对的地方请大家留言指出讨论讨论 ...

  9. C Primer Plus第六版(中文版)编程练习答案(完美修订版)汇总

    //本文是博主编写的C Primer Plus第六版(中文版)编程练习答案的所有链接; //使用超链接汇总于此,若是有用请点赞收藏并分享给他人; C Primer Plus 第六版(中文版)第二章(完 ...

  10. 深夜里学妹竟然问我会不会C?我直接把这篇文章甩她脸上(C Primer Plus 第六版基础整合)

    C Primer Plus 第六版 前言 第一章 初识C语言 一.C语言的起源 二.C语言的应用 三.C语言的特点 四.编译的过程 五.编码机制 1.简述 2.完成机制 六.在UNIX系统上使用C 七 ...

最新文章

  1. 选择Kong作为你的API网关
  2. 关于OKR,你最关心的几个问题,答案在这里
  3. Mybaitis 缓存的优化
  4. 获得AndroidManifest.xml文件中meta-data的value值
  5. vs及番茄助手快捷键使用介绍
  6. 如何添加地图控件到Windows Phone 8的页面中
  7. 华水c语言课程设计,【图片】发几个C语言课程设计源代码(恭喜自己当上技术小吧主)【东华理工大学吧】_百度贴吧...
  8. PLSQL连接ORACLE
  9. leetcode - Search in Rotated Sorted Array II
  10. EasyUI组件使用
  11. netlogo元胞自动机室内疏散
  12. 普通二本毕业八年,京东就职两年、百度三年,分享大厂心得
  13. excel npoi 连接_MVC导出Excel之NPOI简单使用(一)
  14. (8个方法)解决windows11/10/8/7卡在准备就绪一直转圈
  15. BPMN这点事-那段悲催的历史(下)XPDL、BPEL和BPDM之间的恩怨们
  16. Android音视频开发;斗鱼直播实现
  17. 英国内政部(Home Office)间谍机构(spy powers)假装它是Ofcom咨询中的一名私人公民1525446049260...
  18. 搜狗输入法模糊音设置 (非自定义短语设置)
  19. 转帖:还有谁在用王林快码,还有谁记得王林
  20. Python强大的自省机制

热门文章

  1. 文字识别(六)--不定长文字识别CRNN算法详解
  2. SMT 常用术语解释
  3. java开发工具(装机大全)
  4. 论文中引用github项目
  5. 红米note电信版_标注2014910_官方线刷包_救砖包_解账户锁
  6. 百度下拉词用python怎么抓取
  7. 阿里云Docker镜像库
  8. 阿里的Java 开发,拿那么高工资,每天都在干啥?
  9. ADI收购美信,软银欲出售Arm,苹果可能接盘
  10. 基于ESP插件的eCognition多尺度面向对象分割