继承
一(Account类)
1.问题描述
创建一个与银行账户相关的类继承层次。银行的所有账户都可以存款和取款。存款能够产生一定的利息,查询和取款交易要缴纳一定的手续费。
要求:
基类:Account(参考实验提示);
派生类:SavingAccount和CheckingAccount;
SavingAccount:继承Account的成员函数;
构造函数接收两个参数:存款初始值(initialBalance)和利率(rate);增加一个数据成员:利率(interestRate),增加public类型的成员函数用于计算利率(calculateInterest())。
CheckingAccount:构造函数应接收到两个参数,一个是存款初始值(initialBalance),一个是手续费(fee);增加一个数据成员:手续费(transactionFee);重新定义成员函数credit()和debit(),以便能够从存款余额中减去手续费,要求成员函数通过调用基类的成员函数来更新存款数目,debit()函数应该在确定取款之后才能扣除手续费。
2. 实验提示
1)类定义示例:
#ifndef ACCOUNT_H
#define ACCOUNT_H
class Account
{
public:
Account(double ); // constructor initializes balance
void credit( double ); // add an amount to the account balance
bool debit( double ); // subtract an amount from the account balance
void setBalance( double ); // sets the account balance
double getBalance(); // return the account balance
private:
double balance; // data member that stores the balance
}; // end class Account
#endif
//Account.cpp
#include <iostream>
using std::cout;
using std::endl;
#include "Account.h" // include definition of class Account
// Account constructor initializes data member balance
Account::Account( double initialBalance )
{
//if initialBalance is greater than or equal to 0.0, set this value
//as the balance of the Account
if( initialBalance >= 0.0 )
balance = initialBalance;
else // otherwise, output message and set balance to 0.0
{
cout << "Error: Initial balance cannot be negative."<< endl;
balance = 0.0;
}// end if...else
} // end Account constructor
// credit (add) an amount to the accountbalance
void Account::credit( double amount )
{
balance = balance + amount; // add amount to balance
} // end function credit
// debit (subtract) an amount from the account balance
// return bool indicating whether money was debited
bool Account::debit( double amount )
{
if( amount > balance ) // debit amount exceeds balance
{
cout << "Debit amount exceeded account balance."<< endl;
return false;
}// end if
else // debit amount does not exceed balance
{
balance = balance - amount;
return true;
}
// end else
} // end function debit
// set the account balance
void Account::setBalance( double newBalance)
{
balance = newBalance;
} // end function setBalance
// return the account balance
double Account::getBalance()
{
return balance;
} // end function getBalance
2)测试函数示例
int main()
{
Account account1( 50.0 ); // create Account object
SavingsAccount account2( 25.0, .03 ); // create SavingsAccount object
CheckingAccount account3( 80.0, 1.0 ); // create CheckingAccount object
cout << fixed << setprecision( 2 );
//display initial balance of each object
cout << "account1 balance: $" <<account1.getBalance() << endl;
cout << "account2 balance: $" <<account2.getBalance() << endl;
cout << "account3 balance: $" <<account3.getBalance() << endl;
cout << "\nAttempting to debit $25.00 from account1." << endl;
account1.debit( 25.0 ); // try to debit $25.00 from account1
cout << "\nAttempting to debit $30.00 from account2."<< endl;
account2.debit( 30.0 ); // try to debit $30.00 from account2
cout << "\nAttempting to debit $40.00 from account3."<< endl;
account3.debit( 40.0 ); // try to debit $40.00 from account3
//display balances
cout << "\naccount1 balance: $" <<account1.getBalance() << endl;
cout << "account2 balance: $" <<account2.getBalance() << endl;
cout << "account3 balance: $" <<account3.getBalance() << endl;
cout << "\nCrediting $40.00 to account1." << endl;
account1.credit( 40.0 ); // credit $40.00 to account1
cout << "\nCrediting $65.00 to account2." << endl;
account2.credit( 65.0 ); // credit $65.00 to account2
cout << "\nCrediting $20.00 to account3." << endl;
account3.credit( 20.0 ); // credit $20.00 to account3
//display balances
cout << "\naccount1 balance: $" <<account1.getBalance() << endl;
cout << "account2 balance: $" <<account2.getBalance() << endl;
cout << "account3 balance: $" <<account3.getBalance() << endl;
//add interest to SavingsAccount object account2
double interestEarned = account2.calculateInterest();
cout << "\nAdding $" << interestEarned <<" interest to account2."<< endl;
account2.credit( interestEarned );
cout << "\nNew account2 balance: $" <<account2.getBalance() << endl;
return 0;
} // end main
3.结果示例
【我的代码】
//Account.h
#ifndef ACCOUNT_H
#define ACCOUNT_H
class Account
{
public:
Account( double ); // constructor initializes balance
void credit( double ); // add an amount to the account balance
bool debit( double ); // subtract an amount from the account balance
void setBalance( double ); // sets the account balance
double getBalance(); // return the account balance
private:
double balance; // data member that stores the balance
}; // end class Account
#endif
//CheckingAccount.h
#ifndef CHECKINGACCOUNT_H
#define CHECKINGACCOUNT_H
#include"Account.h"
class CheckingAccount:public Account
{
public:
CheckingAccount(double=0.0,double=0.0);
void credit( double );
bool debit( double );
private:
double transactionFee;
};
#endif
//SavingAccount.h
#ifndef SAVINGACCOUNT_H
#define SAVINGACCOUNT_H
#include"Account.h"
class SavingAccount:public Account
{
public:
SavingAccount(double=0.0,double=0.0);
double calculateInterest();
private:
double interestRate;
};
#endif
//Account.cpp
#include <iostream>
using namespace std;
#include "Account.h"
Account::Account( double initialBalance )
{
if ( initialBalance >= 0.0 )
balance = initialBalance;
else
{
cout << "Error: Initial balance cannot be negative." << endl;
balance = 0.0;
}
}
void Account::credit( double amount )
{
balance = balance + amount;
}
bool Account::debit( double amount )
{
if ( amount > balance )
{
cout << "Debit amount exceeded account balance." << endl;
return false;
}
else
{
balance = balance - amount;
return true;
}
}
void Account::setBalance( double newBalance )
{
balance = newBalance;
}
double Account::getBalance()
{
return balance;
}
//CheckingAccount.cpp
#include"CheckingAccount.h"
#include<iostream>
using namespace std;
CheckingAccount::CheckingAccount(double initialBalance,double fee):
Account(initialBalance)
{
transactionFee=fee;
}
void CheckingAccount::credit( double amount)
{
cout<<"$"<<transactionFee<<" transaction fee charged.\n";
Account::credit(amount-transactionFee);
}
bool CheckingAccount::debit( double amount)
{
cout<<"$"<<transactionFee<<" transaction fee charged.\n";
return Account::debit(amount+transactionFee);
}
//SavingAccount.cpp
#include<iostream>
#include"SavingAccount.h"
using namespace std;
SavingAccount::SavingAccount(double initialBalance,double rate):
Account(initialBalance)
{
interestRate=rate;
}
double SavingAccount::calculateInterest()
{
return Account::getBalance()*interestRate;
}
//AccountTest.cpp
#include<iostream>
#include<iomanip>
#include"Account.h"
#include"SavingAccount.h"
#include"CheckingAccount.h"
using namespace std;
int main()
{
Account account1( 50.0 ); // create Account object
SavingAccount account2( 25.0, .03 ); // create SavingsAccount object
CheckingAccount account3( 80.0, 1.0 ); // create CheckingAccount object
cout << fixed << setprecision( 2 );
cout << "account1 balance: $" << account1.getBalance() << endl;
cout << "account2 balance: $" << account2.getBalance() << endl;
cout << "account3 balance: $" << account3.getBalance() << endl;
cout << "\nAttempting to debit $25.00 from account1." << endl;
account1.debit( 25.0 );
cout << "\nAttempting to debit $30.00 from account2." << endl;
account2.debit( 30.0 );
cout << "\nAttempting to debit $40.00 from account3." << endl;
account3.debit( 40.0 );
cout << "\naccount1 balance: $" << account1.getBalance() << endl;
cout << "account2 balance: $" << account2.getBalance() << endl;
cout << "account3 balance: $" << account3.getBalance() << endl;
cout << "\nCrediting $40.00 to account1." << endl;
account1.credit( 40.0 );
cout << "\nCrediting $65.00 to account2." << endl;
account2.credit( 65.0 );
cout << "\nCrediting $20.00 to account3." << endl;
account3.credit( 20.0 );
cout << "\naccount1 balance: $" << account1.getBalance() << endl;
cout << "account2 balance: $" << account2.getBalance() << endl;
cout << "account3 balance: $" << account3.getBalance() << endl;
double interestEarned = account2.calculateInterest();
cout << "\nAdding $" << interestEarned << " interest to account2."
<< endl;
account2.credit( interestEarned );
cout << "\nNew account2 balance: $" << account2.getBalance() << endl;
system("pause");
return 0;
}
二 复习对象的构造和组合关系(Construction and Composition)
Implement Date class and Test class, and make the
main function output correctly. All data members should be private.
Tips:
(1) Data validation is not required.
(2) It is only required to implement the necessary member functions.
(3) Interface and implementation are not necessarily separated.
测试函数
int main()
{
Test test1("C++ Test", Date(2014,6,2));
test1.print();
Test test2("Java");
test2.print();
test2.setDue(Date(2014,6,10));
test2.print();
}
输出
Title: C++ Test
Test Date: 2014-6-2
Title: Java
Test Date: 2014-1-1
Title: Java
Test Date: 2014-6-10
【我的代码】
//Date.h
#ifndef DATE_H
#define DATE_H
class Date
{
public:
Date(int y=2014,int m=1,int d=1)
{
setDate(y,m,d);
}
void setDate(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
int getYear()
{
return year;
}
int getMonth()
{
return month;
}
int getDay()
{
return day;
}
private:
int year,month,day;
};
#endif
//Test.h
#ifndef TEST_H
#define TEST_H
#include<string>
#include<iostream>
#include"Date.h"
using namespace std;
class Test:public Date
{
public:
Test(string name,Date testDay)
{
testName=name;
setDue(testDay);
}
Test(string name)
{
testName=name;
}
void setDue(Date testDay)
{
testDate.setDate(testDay.getYear(),testDay.getMonth(),testDay.getDay());
}
void print()
{
cout<<"Title: "<<testName<<endl<<"Test Date: "
<<testDate.getYear()<<"-"<<testDate.getMonth()<<"-"<<testDate.getDay()<<endl;
}
private:
string testName;
Date testDate;
};
#endif
//Construction and Composition.cpp
#include"Date.h"
#include"Test.h"
int main()
{
Test test1("C++ Test", Date(2014,6,2));
test1.print();
Test test2("Java");
test2.print();
test2.setDue(Date(2014,6,10));
test2.print();
system("pause");
return 0;
}
三: Inheritance,Constructor and Initializer
Design and implement a hierarchical class structure, according to the following requirements.
- Shape is a base class.
- Classes Circle, Triangle and Rectangle are directly inherited from shape.
- Square is directly inherited from Rectangle.
- Provide constructors and destructor for each class.
- Each object must include at least one data member named id (string).
- Objects of derived classes should contain some necessary data members to determine their position and area, such as centerofcircle(circle), lefttop(circle), rightbottom(circle), radius etc.
- Objects of class Square have one special method named incircle. This method can create and return the inscribed circle obejcet(circle) of the corresponding Square object.
- Each object provides area() function to
calculate the area of an shape object and print()function to display all information of an object such as radius, width, length, area and incircle. - Use Initializers to initialize data members of base class and composition objects.
【我的代码】
//Circle.h
#ifndef CIRCLR_H
#define CIRCLR_H
#include"Shape.h"
class Circle:public Shape
{
public:
Circle(string="Circle",double=0.0,double=0.0,double=0.0);
~Circle();
double area();
void print();
private:
double centerX;
double centerY;
double radius;
};
#endif
//Rectangle.h
#ifndef RETANGLE_H
#define RETANGLE_H
#include"Shape.h"
class Rectangle:public Shape
{
public:
Rectangle(string="Rectangle",double=0.0,double=0.0,double=0.0,double=0.0);
~Rectangle();
double getcentreX();
double getcentreY();
double getwidth();
double getlength();
double area();
void print();
private:
double centreX,centreY;
double width;
double length;
};
#endif
//Shape.h
#ifndef SHAPE_H
#define SHAPE_H
#include<string>
using namespace std;
class Shape
{
public:
Shape(string="Shape");
~Shape();
string getId();
private:
string id;
};
#endif
//Square.h
#ifndef SQUARE_H
#define SQUARE_H
#include"Rectangle.h"
#include"Circle.h"
class Square:public Rectangle
{
public:
Square(string="Square",double=0.0,double=0.0,double=0.0);
~Square();
Circle incircle();
void print();
private:
double centreX,centreY;
double size;
};
#endif
//Triangle.h
#ifndef TRIANGLE_H
#define TRIANGLE_H
#include"Shape.h"
class Triangle:public Shape
{
public:
Triangle(string="Triangle",double=0.0,double=0.0,double=0.0,
double=0.0,double=0.0,double=0.0);
~Triangle();
double area();
void print();
private:
double point1X,point1Y;
double point2X,point2Y;
double point3X,point3Y;
};
#endif
//Circle.cpp
#include"Circle.h"
#include<iostream>
#include<cmath>
using namespace std;
Circle::Circle(string id,double r,double cx,double cy):
Shape(id)
{
radius=r;
centerX=cx;
centerY=cy;
}
Circle::~Circle()
{
}
double Circle::area()
{
return 3.14*radius*radius;
}
void Circle::print()
{
cout<<getId()<<":\nRadius: "<<radius
<<"\ncentreofcircle: ("<<centerX<<","<<centerY<<")"
<<"\nLefttop: ("<<centerX-sqrt(2.0)*radius/2<<","<<centerY+sqrt(2.0)*radius/2<<")"
<<"\nRightbottom: ("<<centerX+sqrt(2.0)*radius/2<<","<<centerY-sqrt(2.0)*radius/2<<")"
<<"\nArea: "<<area()<<"\n\n";
}
//Rectangle.cpp
#include"Rectangle.h"
#include<iostream>
using namespace std;
Rectangle::Rectangle(string id,double l,double w,double X,double Y):
Shape(id)
{
length=l;
width=w;
centreX=X;
centreY=Y;
}
Rectangle::~Rectangle()
{
}
double Rectangle::area()
{
return width*length;
}
double Rectangle::getcentreX()
{
return centreX;
}
double Rectangle::getcentreY()
{
return centreY;
}
double Rectangle::getwidth()
{
return width;
}
double Rectangle::getlength()
{
return length;
}
void Rectangle::print()
{
cout<<getId()<<":\nCentreofrectangle: ("<<centreX<<","<<centreY<<")"
<<"\nLenth: "<<length<<"\nWidth: "<<width
<<"\nArea: "<<area()<<"\n\n";
}
//Shape.cpp
#include"Shape.h"
Shape::Shape(string name)
{
id=name;
}
Shape::~Shape()
{
}
string Shape::getId()
{
return id;
}
//Square.cpp
#include"Square.h"
#include"Circle.h"
#include<iostream>
using namespace std;
Square::Square(string id,double s,double x,double y):Rectangle(id,s,s,x,y)
{
}
Square::~Square()
{
}
Circle Square::incircle()
{
Circle inc("The inscribed circle",getwidth()/2,getcentreX(),getcentreY());
return inc;
}
void Square::print()
{
cout<<getId()<<":\nCentreofrectangle: ("<<getcentreX()<<","<<getcentreY()<<")"
<<"\nSize: "<<getlength()
<<"\nArea: "<<area()<<"\n";
incircle().print();
}
//Triangle.cpp
#include"Triangle.h"
#include<iostream>
#include<cmath>
using namespace std;
Triangle::Triangle(string id,double p1X,double p1Y,double p2X,
double p2Y,double p3X,double p3Y):
Shape(id)
{
point1X=p1X;
point1Y=p1Y;
point2X=p2X;
point2Y=p2Y;
point3X=p3X;
point3Y=p3Y;
}
Triangle::~Triangle()
{
}
double Triangle::area()
{
double size1=sqrt(pow(point1X-point2X,2.0)+pow(point1Y-point2Y,2.0));
double size2=sqrt(pow(point1X-point3X,2.0)+pow(point1Y-point3Y,2.0));
double size3=sqrt(pow(point3X-point2X,2.0)+pow(point3Y-point2Y,2.0));
double p=(size1+size2+size3)/2;
return sqrt(p*(p-size1)*(p-size2)*(p-size3));
}
void Triangle::print()
{
cout<<getId()<<":\nPoint1: ("<<point1X<<","<<point1Y<<")"
<<"\nPoint2: ("<<point2X<<","<<point2Y<<")"
<<"\nPoint3: ("<<point3X<<","<<point3Y<<")"
<<"\nArea: "<<area()<<"\n\n";
}
//squareTest.cpp
#include"Circle.h"
#include"Rectangle.h"
#include"Square.h"
#include"Triangle.h"
int main()
{
Circle shape1("Shape1(circle)",1.0,1.0,1.0);
Triangle shape2("Shape2(triangle)",2.0,0.0,3.0,2.0,4.0,0.0);
Rectangle shape3("Shape3(rectangle)",6.0,2.0,2.0,4.0);
Square shape4("Shape4(square)",2.0,1.0,5.0);
shape1.print();
shape2.print();
shape3.print();
shape4.print();
system("pause");
return 0;
}