C++primer plus第六版课后编程题答案10.1
bank.h
#ifndef bank_H_ #define bank_H_ #include <string> using namespace std; class Bank{ private: string name; string account; double money; void setIn(double in){money+=in;}; void setOut(double out){money-=out;}; double getMoney(){return money;}; public: Bank(string n,string a,double m); ~Bank(); //void show(const bank &b); void in(double input); void out(double output); friend ostream&operator<<(ostream &os,const Bank &b);//友元函数 }; #endif
bank.cpp
#include <iostream> #include "bank.h" Bank::Bank(string n,string a,double m){ name=n; //怎么第一次编译老是提示我构造函数不能有返回值? account=a; money=m; std::cout<<"\nBankaccount success!"<<endl; } /* Bank::Bank(string n,string a,double m) { name=n; account=a; money=m; std::cout<<"Success!"<<endl; }*/ Bank::~Bank() { std::cout<<"\nBankaccount recevory!"<<endl; } void Bank::in(double input) { Bank::setIn(input); } void Bank::out(double output) { if(Bank::getMoney()>0) Bank::setOut(output); else std::cout<<"\nYour have not enough money!"<<endl; } std::ostream &operator<<(ostream &os,const Bank &b)//重载<<运算符 { os<<"\nshow start!"<<endl; os<<"name:"<<b.name<<" account:"<<b.account<<endl; os<<"money:"<<b.money<<endl; return os; }
main101.cpp
#include <iostream> #include "bank.h" using namespace std; void main101() { { //将其加入代码块是为了更好地查看对象的销毁过程 Bank b1=Bank("guang","a1",100); Bank b2=Bank("jing","a2",600.5); cout<<b1<<endl; cout<<b2<<endl; //b1.money=200; b1.in(100); cout<<b1<<endl; b1.out(5.5); cout<<b1<<endl; } system("pause"); }