【C++】C++PrimerPlus(第6版)中文版 第10章 对象和类 编程练习 参考答案

自己编写的参考答案,在VS2019中都可以编译通过,不是标准答案,也不是最优答案,仅供参考

1.为复习题5描述的类提供方法定义,并编写一个小程序来演示所有的特性。
.h:
#pragma once
#include<iostream>
using namespace std;
class BankAccount
{
private:
    char name[40];
    char acctnum[25];
    double balance;
public:
    BankAccount(const char* client, const char* num, double bal = 0.0);
    void show(void) const;
    void deposit(double cash);
    void withdraw(double cash);
};
.cpp:
#include"Topic1.h"
BankAccount::BankAccount(const char* client, const char* num, double bal)
{
 strncpy_s(this->name, 40, client, sizeof(client));
 strncpy_s(this->acctnum, 25, num, strlen(num)+1);
 this->balance = bal;
}
void BankAccount::show(void) const
{
 cout << "储户姓名:"<< this->name << endl;
 cout << "储户账号:" << this->acctnum << endl;
 cout << "储户存款:" << this->balance << endl;
}
void BankAccount::deposit(double cash)
{
 this->balance += cash;
 cout << "已存入" << cash << endl;
}
void BankAccount::withdraw(double cash)
{
 if (this->balance>=cash)
 {
  this->balance -= cash;
  cout << "已取出" << cash << endl;
 }
 else
 {
  cout << "余额不足" <<cash<< endl;
 }

}
主文件:
#include <iostream>
#include"Topic1.h"
using namespace std;
int main()
{
 BankAccount bank01 = { "马云","10086" };
 bank01.show();
 bank01.deposit(200);
 bank01.show();
 bank01.withdraw(100);
 bank01.show();
 bank01.withdraw(1000);
 bank01.show();
}
2.下面是一个非常简单的类定义
class Person
{
private:
static const int LIMIT = 25;
string lname; // Person’s last name
char fname[LIMIT]; // Person’s first name
public:
Person() { lname = “”; fname[0] = ‘\0’; } // #1
Person(const string& ln, const char* fn = “Heyyou”); // #2
// the following methods display lname and fname
void Show() const; // firstname lastname format
void FormalShow() const; // lastname, firstname format
};
它使用了一个string对象和一个字符数组,让您能够比较它们的用法。请提供未定义的方法的代码,以完成这个类的实现。再编写一个使用这个类的程序,它使用了三种可能的构造函数的调用(没有参数、一个参数和两个参数)以及两种显示方法。下面是一个使用这些构造函数和方法的例子:
Person one; // use default constructor
Person two(“Smythecraft”);
// use #2 with one default argument
Person three(“Dimwiddy”, “Sam”);
// use #2, no defaults one.Show();
cout << endl;
one.FormalShow();
.h:
#pragma once
#include <iostream>
using namespace std;
class Person
{
private:
    static const int LIMIT = 25;
    string lname;                     // Person’s last name 
    char fname[LIMIT];            // Person’s first name
public:
    Person() { lname = "abc"; fname[0] = '\0'; }                    // #1 
    Person(const string& ln, const char* fn = "Heyyou");      // #2
    // the following methods display lname and fname
    void Show() const;        // firstname, lastname format
    void FormalShow() const;  // lastname, firstname format
};
.cpp:
#include "Topic2.h"
Person::Person(const string& ln, const char* fn)
{
 this->lname = ln;
 strncpy_s(this->fname, 25, fn, sizeof(fn) + 1);
}
void Person::Show() const
{
 cout << this->fname << "   " << this->lname<<endl;
}
void Person::FormalShow() const
{
 cout << this->lname << "   " << this->fname << endl;
}
主文件:
#include <iostream>
#include"Topic2.h"
using namespace std;
int main()
{
 Person one;                        
 Person two("Smythecraft");         
 Person three("Dimwiddy", "Sam");  
 one.Show();
 one.FormalShow();
 two.Show();
 two.FormalShow();
 three.Show();
 three.FormalShow();
}
3.完成第9章的编程练习1,但要用正确的golf类声明替换那里的代码。用带合适参数的构造函数替换setgolf(golf&, const char*, int),以提供初始值。保留setgolf()的交互版本,但要用构造函数来实现它(例如,setgolf()的代码应该获得数据,将数据传递给构造函数来创建一个临时对象,并将其赋给调用对象,即* this)
.h:
#pragma once
#include<iostream>
using namespace std;
class Golf
{
private:
    static const int Len = 40;
    char fullname[Len];
    int handicap;
public:
    Golf(const char* name="Tiger", int hc=9);
    Golf(char name[40], int hc);
    void changehandicap(int hc);
    void showgolf()const;
};
.cpp:
#include "Topic3.h"
Golf::Golf(const char* name, int hc)
{
 strncpy_s(this->fullname, 40, name, sizeof(name)+1);
 this->handicap = hc;
}
Golf::Golf(char name[40], int hc)
{
 cin.get(name, 39);
 (cin >> hc).get();
 strncpy_s(this->fullname, 40, name, sizeof(name) + 1);
 this->handicap = hc;
}
void Golf::changehandicap(int hc)
{
 this->handicap = hc;
}
void Golf::showgolf() const
{
 cout << "选手姓名:" << this->fullname << endl;
 cout << "选手等级:" << this->handicap << endl;
}
主文件:
#include <iostream>
#include "Topic3.h"
using namespace std;
int main()
{
 Golf golf01;
 Golf golf02("abc", 6);
 golf01.showgolf();
 golf02.showgolf();
 golf02.changehandicap(5);
 golf02.showgolf();
}
4. 完成第九章编程练习4,但将Sales结构及相关的函数转换为一个类及其方法。用构造函数替换setSales(sales&, double[], int)函数。用构造函数实现setSales(Sales&)方法的交互版本。将类保留在名称空间SALES中。
.h:
#pragma once
#include<iostream>
using namespace std;
namespace SALES
{
    const double abc[3] = { 10.2,11.3,8.8 };
    class Sales
    {
    private:
        static const int QUARTERS = 4;
        double sales[QUARTERS];
        double average;
        double max;
        double min;
    public:
        Sales(const double ar[] = abc, int n= 3);
        Sales(double ar[4]);
        void showSales()const;
    };
}
.cpp:
#include "Topic4.h"
namespace SALES
{
 Sales::Sales(const double ar[], int n)
 {
  if (n == 4)
  {
   double sum = 0;
   double max = ar[0];
   double min = ar[0];
   for (int i = 0; i < 4; i++)
   {
    this->sales[i] = ar[i];
    sum += ar[i];
   }
   this->average = sum / 4;
   for (int i = 0; i < 4; i++)
   {
    max >= ar[i] ? max = max : max = ar[i];
   }
   for (int i = 0; i < 4; i++)
   {
    min <= ar[i] ? min = min : min = ar[i];
   }
   this->max = max;
   this->min = min;
  }
  else if (n < 4)
  {
   double sum = 0;
   double max = ar[0];
   double min = ar[0];
   for (int i = 0; i < n; i++)
   {
    this->sales[i] = ar[i];
    sum += ar[i];
   }
   for (int i = n; i < 4; i++)
   {
    this->sales[i] = 0;
   }
   this->average = sum / n;
   for (int i = 0; i < n; i++)
   {
    max >= ar[i] ? max = max : max = ar[i];
   }
   for (int i = 0; i < n; i++)
   {
    min <= ar[i] ? min = min : min = ar[i];
   }
   this->max = max;
   this->min = min;
  }
 }
 Sales::Sales(double ar[4])
 {
  double sum = 0;
  double max = ar[0];
  double min = ar[0];
  for (int i = 0; i < 4; i++)
  {
   this->sales[i] = ar[i];
   sum += ar[i];
  }
  this->average = sum / 4;
  for (int i = 0; i < 4; i++)
  {
   max >= ar[i] ? max = max : max = ar[i];
  }
  for (int i = 0; i < 4; i++)
  {
   min <= ar[i] ? min = min : min = ar[i];
  }
  this->max = max;
  this->min = min;
 }
 void Sales::showSales() const
 {
  cout << "四个季度的销售额分别为:";
  for (int i = 0; i < 4; i++)
  {
   cout << this->sales[i] << "   ";
  }
  cout << endl;
  cout << "四个季度的销售额平均值为:";
  cout << this->average << endl;
  cout << "四个季度的销售额最大值为:";
  cout << this->max << endl;
  cout << "四个季度的销售额最小值为:";
  cout << this->min << endl;
 }
}
主文件:
#include<iostream>
#include "Topic4.h"
using namespace std;
using namespace SALES;
int main()
{
 double abc[4] = { 10.0,11.2,13.5,9.8 };
 Sales s1;
 Sales s2 (abc);
 s1.showSales();
 s2.showSales();
}
5. 考虑下面的结构声明:
struct customer {
char fullname[35];
double payment;
};
编写一个程序,它从栈中添加和删除customer结构(栈用Stack类声明表示)。每次customer结构被删除时,其payment的值都将被加入到总数中,并报告总数。注意:应该可以直接使用Stack类而不作修改;只需修改typedef声明,使Item的类型为customer,而不是unsigned long即可。
.h:
#pragma once
struct customer {
    char fullname[35];
    double payment;
};
typedef customer Item;
class Stack
{
private:
    enum { MAX = 10 };    
    Item items[MAX];    
    int top;           
public:
    Stack();
    bool isempty() const;
    bool isfull() const;
    bool push(const Item& item);   
    bool pop(Item& item);          
};
.cpp:
#include "Topic5.h"
Stack::Stack()    // create an empty stack
{
    top = 0;
}
bool Stack::isempty() const
{
    return top == 0;
}
bool Stack::isfull() const
{
    return top == MAX;
}
bool Stack::push(const Item& item)
{
    if (top < MAX)
    {
        items[top++] = item;
        return true;
    }
    else
        return false;
}
bool Stack::pop(Item& item)
{
    if (top > 0)
    {
        item = items[--top];
        return true;
    }
    else
        return false;
}
主文件:
#include <iostream>
#include <cctype> 
#include "Topic5.h"
using namespace std;
int main()
{
    Stack st; // create an empty stack
    char ch;
    customer po;
    double sum = 0;
    cout << "Please enter A to add a purchase order,\n"
         << "P to process a PO, or Q to quit.\n";
    while (cin >> ch && toupper(ch) != 'Q')
    {
        while (cin.get() != '\n')
            continue;
        if (!isalpha(ch))
        {
            cout << '\a';
            continue;
        }
        switch (ch)
        {
        case 'A':
        case 'a': 
            cout << "Enter a PO to add: \n";
            cout << "Enter the fullname of PO: ";
            cin.getline(po.fullname, 35);
            cout << "Enter the payment of PO: ";
            (cin >> po.payment).get();
            if (st.isfull())
                cout << "stack already full\n";
            else
                st.push(po);
            break;
        case 'P':
        case 'p': 
            if (st.isempty())
            cout << "stack already empty\n";
            else 
            {
            st.pop(po);
            cout << "PO #" << po.fullname << " popped\n";
            sum += po.payment;
            cout << "Now, Sum is " << sum << endl;
             }
            break;
        }
        cout << "Please enter A to add a purchase order,\n"
             << "P to process a PO, or Q to quit.\n";
    }
    cout << "Bye\n";
    return 0;
}
6.下面是一个类声明:
class Move
{
private:
double x;
double y;
public:
Move(double a = 0, double b = 0); // sets x, y to a, b
showmove() const; // shows current x,y values
Move add(const Move& m) const;
// this function adds x of m to x of invoking object to get new x,
// adds y of m to y of invoking object to get new y, creates a new
// move object initialized to new x, y values and returns it
reset(double a = 0, double b = 0); // resets x,y to a, b
};
请提供成员函数的定义和测试这个类的程序。
.h:
#pragma once
#include<iostream>
using namespace std;
class Move
{
private:
    double x;
    double y;
public:
    Move(double a = 0, double b = 0);       // sets x, y to a, b
    void showmove() const;                       // shows current x,y values
    Move add(const Move& m) const;
    // this function adds x of m to x of invoking object to get new x, 
    // adds y of m to y of invoking object to get new y, creates a new 
    // move object initialized to new x, y values and returns it
    void reset(double a = 0, double b = 0);      // resets x,y to a, b
};
.cpp:
#include "Topic6.h"
Move::Move(double a, double b)
{
 x = a;
 y = b;
}
void Move::showmove() const
{
 cout << "x坐标为:" << x << "   ";
 cout << "y坐标为:" << y << endl;
}
Move Move::add(const Move& m) const
{
 return Move(m.x,m.y);
}
void Move::reset(double a, double b)
{
 x = a;
 y = b;
}
主文件:
#include "Topic6.h"
int main()
{
 Move m1;
 m1.showmove();
 Move m2(1,1);
 m2.showmove();
 m2=m2.add(m1);
 m2.showmove();
 Move m3(2, 2);
 m3.showmove();
 m3.reset();
 m3.showmove();
}
7.Betelgeusean plorg有这些特征。
数据:
·plorg的名称不超过19个字符
·plorg的满意指数(CI),这是一个整数
操作:
·新的plorg将有名称,其CI值为50
·plorg的CI可以修改
·plorg可以报告其名称和CI
·plorg的默认名称为“Plorga”
请编写一个Plorg类声明(包括数据成员和成员函数原型)来表示plorg,并编写成员函数的函数定义。然后编写一个小程序,以演示Plorg类的所有特性。
.h:
#pragma once
#include<iostream>
using namespace std;
class PLORGA
{
private:
 static const int namesize = 20;
 char name[namesize];
 int CI;
public:
 PLORGA(const char*name02="Plorga",int CI02 =50);
 void showplgera();
 void changeCI(int CI02);
};
.cpp:
#include "Topic7.h"
PLORGA::PLORGA(const char* name02, int CI02)
{
 if (strlen(name02)>19)
 {
  cout << "该名称超过了19个字符,不符合规定";
 }
 else if (strlen(name02)>0 && strlen(name02)<=19)
 {
  strncpy_s(this->name, namesize, name02, sizeof(name02));
  this->CI = CI02;
 }
}
void PLORGA::showplgera()
{
 cout << "名字为:" << name << ",满意指数为:" << CI<<endl;
}
void PLORGA::changeCI(int CI02)
{
 this->CI = CI02;
}
主文件:
#include "Topic7.h"
int main()
{
 PLORGA p1;
 p1.showplgera();
 p1.changeCI(20);
 p1.showplgera();
}
8.可以将简单列表描述成下面这样
·可存储0或多个某种类型的列表
·可创建空列表
·可在列表中添加数据项
·可确定列表是否为空
·可确定列表是否为满
·可访问列表中的每一个数据项,并对它执行某种操作
可以看到,这个列表确实很简单,例如,它不允许插入或删除数据项请设计一个List类来表示这种抽象类型。您应提供头文件list.h和实现文件list.cpp,前者包含类定义,后者包含类方法的实现。您还应该创建一个简短的程序来使用这个类该列表的规范很简单,这个主要旨在简化这个编程练习。可以选择使用数组或链表来实现该列表,但公有接口不应依赖于所做的选择。也就是说,公有接口不应有数组索引、节点指针等。应使用通用概念来表达创建列表、在列表中添加数据项等操作。对于访问数据项以及执行操作,通常应使用将函数指针作为参数的函数来处理:void visit(void (*pf)(Item&));其中。pf指向一个将Item引用作为参数的函数(而不是成员函数),Item是列表中数据项的类型。visit()函数将该函数用于列表中的每个数据项。
.h:
#pragma once
#include<iostream>
using namespace std;
typedef int Item;
class List
{
private:
 static const int num = 20;
 Item list[num];
 int p;
public:
 List();
 void addItem(Item a);
 bool isempty();
 bool isfull();
 void visit(void (*pf)(Item&));
};
.cpp:
#include "Topic8.h"
List::List()
{
 p = 0;
}
void List::addItem(Item a)
{
 if (p<=num-1&&p>=0)
 {
  list[p] = a;
  ++p;
 }
 else
 {
  cout << "无法添加";
 }
}
bool List::isempty()
{
 if (p==0)
 {
  return true;
 }
 else
 {
  return false;
 }
 
}
bool List::isfull()
{
 if (p == num)
 {
  return true;
 }
 else
 {
  return false;
 }
}
void List::visit(void(*pf)(Item&))
{
 pf(list[p-1]);
}
主文件:
#include "Topic8.h"
void add(Item& a)
{
 a += 10;
 cout << a<<endl;
}
void leess(Item& a)
{
 a -= 10;
 cout << a << endl;
}
int main()
{
 List L1;
 cout << L1.isempty() << "   " << L1.isfull() << endl;
 for (int i = 0; i < 20; i++)
 {
  L1.addItem(i);
 }
 cout << L1.isempty() << "   " << L1.isfull() << endl;
 L1.visit(add);
 L1.visit(leess);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值