C++ Primer Plus章节编程练习(第十章)

1、为复习题5描述的类提供方法定义,并编写一个小程序来演示所有特性。

   复习题5:定义一个类来表示银行账户。数据成员包括储户姓名、账号(使用字符串)和存款。成员函数执行如下操作

  ~创建一个对象并将其初始化;

  ~显示储户姓名、账号和存款;

  ~存入参数指定的存款;

  ~取出参数指定的存款。

//account.h
#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <string>
class Account {
private:
    std::string name;
    std::string number;
    double deposit;
public:
    Account(std::string _name, std::string _number = "Error", double _deposit = 0);
    void show() const;
    void save_money(double money);
    void draw_money(double money);
};
#endif // !ACCOUNT_H


//Account.cpp
#include "stdafx.h"
#include "account.h"
#include <iostream>
#include <string>
Account::Account(std::string _name, std::string _number, double _deposit) {
    name = _name;
    number = _number;
    deposit = _deposit;
}

void Account::show() const{
    using std::cout;
    cout << "Name: " << name << "\n"
        << "Number: " << number << "\n"
        << "Deposit: " << deposit << "\n";
}

void Account::save_money(double money) {
    if (number == "Error")
        std::cout << "Wrong ! ";
    else
        deposit += money;
}

void Account::draw_money(double money) {
    if (number == "Error")
        std::cout << "Wrong !";
    else if (deposit < money)
        std::cout << "You have no enough money!";
    else
        deposit -= money;
}


//main.cpp
#include "stdafx.h"
#include "account.h"
int main()
{
    Account test = Account("Tony Hust", "M201876177", 5000.00);
    test.show();
    test.save_money(998.37);
    test.show();
    test.draw_money(100000.00);
    test.show();
    test.draw_money(2554.73);
    test.show();
    return 0;
}

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

//person.h
#ifndef PERSON_H
#define PERSON_H
#include <string>
class Person {
private:
    static const int LIMIT = 25;
    std::string lname;
    char fname[LIMIT];
public:
    Person() { lname = "", fname[0] = '\0'; }
    Person(const std::string & ln, const char * fn = "Heyyou");
    void Show() const;
    void FormalShow() const;
};
#endif // !PERSON_H


//Person.cpp
#include "stdafx.h"
#include "person.h"
#include <iostream>
#include <string>
Person::Person(const std::string & ln, const char * fn) {
    lname = ln;
    strncpy_s(fname, fn, LIMIT);
}

void Person::Show() const{
    std::cout << "Name: " << fname << " " << lname << std::endl;
}

void Person::FormalShow() const{
    std::cout << "Name: " << lname << ", " << fname << std::endl;
}


//main.cpp
#include "stdafx.h"
#include "person.h"
#include <iostream>

int main()
{
    Person one;
    Person two("Smythecraft");
    Person three("Dimwiddy", "Sam");
    one.Show();
    one.FormalShow();
    std::cout << std::endl;
    two.Show();
    two.FormalShow();
    std::cout << std::endl;
    three.Show();
    three.FormalShow();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/SChenqi/p/9778218.html