1.
//头文件stock00.h
#ifndef STOCK00_H_
#define STOCK00_H_
#include<cstring>
// class definition
class BankAccount
{
private:
char name[40]; //or std::string name;
char acctnum[25]; //or std::string acctnum;
double balance;
public:
BankAccount(const char *client, const char *num, double bal = 0.0);
//or BankAccount(const std::string & client, const std::string & num,double bal=0.0);
void show(void) const;
void deposit(double cash);
void withdraw(double cash);
};
#endif
//类定义stock00.cpp
#include<iostream>
#include<cstring>
#include"stock00.h"
BankAccount::BankAccount(const char * client, const char * num, double bal)
{
strncpy(name, client,39); //直接赋值
name[39]='\0';
strncpy(acctnum, num,24);
acctnum[24]='\0';
balance = bal;
}
void BankAccount::deposit(double cash)
{
using std::cout;
if (cash < 0)
{
cout << "Number of cash can't be negative.\n";
}
else
balance += cash;
}
void BankAccount::withdraw(double cash)
{
using std::cout;
if (cash < 0)
{
cout << "Number of cash can't be negative.\n";
}
else if (cash > balance)
cout << "You can't get more than you have!\n";
else
balance -= cash;
}
void BankAccount::show(void) const
{
std::cout << "Name: " << name << '\n'
<< "AcctNum: " << acctnum << '\n'
<< "Balance: " << balance << '\n';
}
//主函数usestock0.cpp
#include<iostream>
#include "stock00.h"
int main()
{
using std::cout;
cout << "Bank Account information:\n";
BankAccount b1("huangfu shuyun", "ZHT", 1200);
b1.show();
BankAccount b2("zhao qian", "PTO", 5000);
b2.show();
cout << "\nAfter a month:\n";
b1.deposit(1000);
b1.show();
b1.withdraw(2000);
b1.show();
b2.withdraw(500);
b2.show();
b2.deposit(2000);
b2.show();
return 0;
}
2.
//头文件stock00.h
#ifndef STOCK00_H_
#define STOCK00_H_
#include<string>
using namespace std;
// class definition
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
};
#endif
//类定义stock00.cpp
#include<iostream>
#include<string>
#include<cstring>
#include"stock00.h"
Person::Person(const string & ln,const char *fn)
{
lname = ln;
strcpy_s(fname, fn);
}
void Person::Show() const
{
std::cout << "Full Name:" << std::end