1. 程式人生 > >C++ Primer Plus章節編程練習(第十章)

C++ Primer Plus章節編程練習(第十章)

amp formal main.c one 取出 賬戶 form ios oid

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;
}

C++ Primer Plus章節編程練習(第十章)