第4章类与对象
约 2584 字大约 9 分钟
2026-11-10
4-1 时钟类的完整程序
/*
4-1 P105
时钟类的完整程序
*/
#include<iostream>
#include<cstdlib>
using namespace std;
class Clock{ //时钟类的定义
public: //外部接口,公有成员函数
void setTime(int newH=0,int newM=0,int newS=0);
void showTime();
private: //私有数据成员
int hour,minute,second;
};
//时钟类成员函数的具体实现
void Clock::setTime(int newH,int newM,int newS){
hour=newH;
minute=newM;
second=newS;
}
inline void Clock::showTime(){
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
int main()
{
Clock myClock; //定义对象myClock
cout<<"First time set and output:"<<endl;
myClock.setTime(); //设置时间为默认值
myClock.showTime(); //显示时间
cout<<"Second time set and output:"<<endl;
myClock.setTime(8,30,30); //设置时间为8:30:30
myClock.showTime(); //显示时间
system("pause");
return 0;
}4-1-1 时钟类的完整程序-补充了构造函数
/*
4-1-1 P108
时钟类的完整程序-补充了构造函数
*/
#include<iostream>
#include<cstdlib>
using namespace std;
class Clock{ //时钟类的定义
public: //外部接口,公有成员函数
Clock(int newH,int newM,int newS); //构造函数
void setTime(int newH,int newM,int newS);
void showTime();
private: //私有数据成员
int hour,minute,second;
};
//时钟类成员函数的具体实现
void Clock::setTime(int newH,int newM,int newS){
hour=newH;
minute=newM;
second=newS;
}
inline void Clock::showTime(){
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
//构造函数的实现
Clock::Clock(int newH,int newM,int newS):hour(newH),minute(newM),second(newS)
{}
int main()
{
Clock c(0,0,0);
c.showTime();
c.setTime(8,30,30);
c.showTime();
system("pause");
return 0;
}4-1-2 默认构造函数,委托构造函数
/*
4-1-2 P109
默认构造函数,委托构造函数
*/
#include<iostream>
#include<cstdlib>
using namespace std;
//时钟类
class Clock{
public:
Clock(int newH,int newM,int newS); //构造函数
Clock(); //默认构造函数
Clock(int x); //委托构造函数,将小时初始化为x
void setTime(int newH,int newM,int newS);
void showTime();
private:
int hour,minute,second;
};
//构造函数
Clock::Clock(int newH,int newM,int newS):hour(newH),minute(newM),second(newS)
{}
//默认构造函数
Clock::Clock():hour(0),minute(0),second(0)
{}
// //默认构造函数-委托构造函数
// Clock::Clock():Clock(0,0,0)
// {}
//委托构造函数
Clock::Clock(int x):Clock(x,0,0)
{}
//设置时间
void Clock::setTime(int newH,int newM,int newS){
hour=newH;
minute=newM;
second=newS;
}
//显示时间
inline void Clock::showTime(){
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
int main()
{
Clock c1(1,0,0);
Clock c2;
Clock c3(8);
c1.showTime();
c2.showTime();
c3.showTime();
system("pause");
return 0;
}4-2 复制构造函数
/*
4-2 P112
复制构造函数
*/
#include<iostream>
#include<cstdlib>
using namespace std;
//Point类
class Point{
public: //外部接口
Point(int xx=0,int yy=0){ //构造函数
x=xx;y=yy;
}
Point(Point &p); //复制构造函数
int getX(){
return x;
}
int getY(){
return y;
}
private:
int x,y;
};
//复制构造函数的实现
Point::Point(Point &p){
x=p.x;
y=p.y;
cout<<"Calling the copy constructor"<<endl;
}
//形参为Point类对象的函数
void fun1(Point p){
cout<<p.getX()<<","<<p.getY()<<endl;
}
//返回值为Point类对象的函数
Point fun2(){
Point a(1,2);
return a;
}
int main()
{
Point a(4,5); //第一个对象a
Point b{a}; //情况一,用a初始化b。第一次调用复制构造函数
cout<<b.getX()<<","<<b.getY()<<endl;
fun1(b); //情况二,对象作为fun1的实参。第二次调用复制构造函数
b=fun2(); //情况三,函数的返回值是类对象,函数返回时,调用复制构造函数
cout<<b.getX()<<","<<b.getY()<<endl;
system("pause");
return 0;
}4-3 游泳池改造预算,Circle类
/*
4-3 P117
游泳池改造预算,Circle类
*/
#include<iostream>
#include<cstdlib>
using namespace std;
const float PI=3.141593; //圆周率PI的值
const float FENCE_PRICE=35; //栅栏的单价
const float CONCRETE_PRICE=20; //过道水泥单价
//Circle类
class Circle{ //声明定义类Circle及其数据和方法
public: //外部接口
Circle(float r); //构造函数
float circumference(); //计算圆的周长
float area(); //计算圆的面积
private: //私有数据成员
float radius; //圆的半径
};
//构造函数
Circle::Circle(float r):radius(r)
{}
//圆的周长
float Circle::circumference(){
return 2*PI*radius;
}
//圆的半径
float Circle::area(){
return PI*radius*radius;
}
int main()
{
//用户输入数据
float radius;
cout<<"Enter the radius of the pool:";//提示用户输入数据
cin>>radius;
//定义泳池边界和栅栏对象
Circle pool(radius); //游泳池边界
Circle poolRim(radius+3); //栅栏对象
//计算栅栏造价并输出
float fenceCost=poolRim.circumference()*FENCE_PRICE;
cout<<"Fencing Cost is $ "<<fenceCost<<endl;
//计算过道造价并输出
float concreteCost=(poolRim.area()-pool.area())*CONCRETE_PRICE;
cout<<"Concrete Cost is $ "<<concreteCost<<endl;
system("pause");
return 0;
}4-4 类的组合,线段(Line)类
/*
4-4 P121
类的组合,线段(Line)类
*/
#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
//Point类
class Point{
public: //外部接口
Point(int xx=0,int yy=0){ //构造函数
x=xx;y=yy;
}
Point(Point &p); //复制构造函数
int getX(){return x;}
int getY(){return y;}
private:
int x,y;
};
//Point复制构造函数的实现
Point::Point(Point &p){
x=p.x;
y=p.y;
cout<<"Calling the copy constructor of Point"<<endl;
}
//类的组合
class Line{
public:
Line(Point xp1,Point xp2);
Line(Line &l);
double gerLen(){return len;}
private:
Point p1,p2;
double len;
};
//组合类的构造函数
Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2){
//p1=xp1;p2=xp2;
cout<<"Calling constructor of Line"<<endl;
double x=static_cast<double>(p1.getX()-p2.getX());
double y=static_cast<double>(p1.getY()-p2.getY());
len=sqrt(x*x+y*y);
}
//组合类的复制构造函数
Line::Line(Line &l):p1(l.p1),p2(l.p2){
cout<<"Calling the copy constructor of Line"<<endl;
len=l.len;
}
int main()
{
//定义两个Point类的对象
Point myp1(1,1),myp2(4,5);
//用Point类的对象定义Line类的对象
Line line(myp1,myp2);
Line line2(line);
cout<<"The length of the line is: ";
cout<<line.gerLen()<<endl;
cout<<"The length of the line2 is: ";
cout<<line2.gerLen()<<endl;
system("pause");
return 0;
}4.5 P129 采用UML的方法来描述例4-4中Line类和Point类的关系
采用UML的方法来描述例4-4中Line类和Point类的关系 使用vscode中的plantuml插件完成
@startuml Line & Point
class Line{
- len:double
+ Line(xp1:Point,xp2:Point)
+ Line(:Line &)
+ getLen():double
}
class Point{
- x:int
- y:int
+ Point(xx:int=0,yy:int=0)
+ Point(P:Point&)
+ getX():int
+ getY():int
}
Line "1..*" *--> "2"Point
Line ..|> Point
@enduml4.6 P129 带有注释的Line类和Point类关系的描述
带有注释的Line类和Point类关系的描述 使用vscode中的plantuml插件完成
@startuml Line & Point
class Line{
- len:double
+ Line(xp1:Point,xp2:Point)
+ Line(:Line &)
+ getLen():double
}
class Point{
- x:int
- y:int
+ Point(xx:int=0,yy:int=0)
+ Point(P:Point&)
+ getX():int
+ getY():int
}
Line "1..*" *--> "2"Point
note on link : 单向组合:\n直线段包含\n端点p1,p2
Line ..|> Point
@enduml4.7 用结构体表示学生的基本信息
/*
4-7 P132
用结构体表示学生的基本信息
*/
#include<iostream>
//#include<iomanip>
#include<string>
using namespace std;
struct Student
{
int num;
string name;
char sex;
int age;
};
int main()
{
Student stu={97001,"Lin Lin",'F',19};
cout<<"Num: "<<stu.num<<endl;
cout<<"Name: "<<stu.name<<endl;
cout<<"Sex: "<<stu.sex<<endl;
cout<<"age: "<<stu.age<<endl;
getchar();//程序暂停
return 0;
}4.8 使用联合体保存成绩信息,并且输出
/*
4-8 P134
使用联合体保存成绩信息,并且输出
*/
#include<iostream>
#include<string>
using namespace std;
class ExamInfo{
public:
//三种构造函数,分别用等级、是否通过和百分来初始化
ExamInfo(string name,char grade):name(name),mode(GRADE),grade(grade){}
ExamInfo(string name,bool pass):name(name),mode(PASS),pass(pass){}
ExamInfo(string name,int percent):name(name),mode(PERCENTAGE),percent(percent){}
void show();
private:
string name; //课程名称
enum {
GRADE,
PASS,
PERCENTAGE
}mode; //采用何种计分方式
union{
char grade; //等级制的成绩
bool pass; //是否通过
int percent; //百分制的成绩
};
};
void ExamInfo::show(){
cout<<name<<": ";
switch(mode)
{
case GRADE:
cout<<grade;
break;
case PASS:
cout<<(pass?"PASS":"FAIL");
break;
case PERCENTAGE:
cout<<percent;
break;
}
cout<<endl;
}
int main()
{
ExamInfo course1("English",'B');
ExamInfo course2("Calculus",true);
ExamInfo course3("C++Programming",85);
course1.show();
course2.show();
course3.show();
getchar();//程序暂停
return 0;
}4-9 编写程序顺序输出枚举的四种情况
/*
4-9 P137
设某次体育比赛的结果有四种可能:胜(WIN)、负(LOSE)、平局(TIE)、比赛取消(CANCEL),
编写程序顺序输出这四种情况
*/
#include<iostream>
using namespace std;
enum GameResult{WIN,LOSE,TIE,CANCEL};
int main()
{
GameResult result; //声明变量时,可以不写关键字enum
enum GameResult omit=CANCEL; //也可以在类型名前写关键字enum
for(int count=WIN;count<=CANCEL;count++)//隐含类型转换
{
result=GameResult(count);//显式类型转换
if(result==omit)
cout<<"The game was cancelled"<<endl;
else
{
cout<<"The game was played ";
if(result==WIN)
cout<<"and we won!";
if(result==LOSE)
cout<<"and we lost.";
cout<<endl;
}
}
getchar();//程序暂停
return 0;
}4-10 综合实例-个人银行账户管理程序
/*
4-10 P139
综合实例-个人银行账户管理程序
*/
#include<iostream>
#include<cmath>
using namespace std;
class SavingsAccount{ //储蓄账户类
private:
int id; //账号
double balance; //余额
double rate; //存款的年利率
int lastDate; //上次变更余额的日期
double accumulation; //余额按日累加之和
//记录一笔账,date为日期,amount为金额,desc为说明
void record(int date,double amount);
//获得到指定日期为止的存款金额按日累积值
double accumulate(int date)const{
return accumulation+balance*(date-lastDate);
}
public:
//构造函数
SavingsAccount(int date,int id,double rate);
//获取账户信息(数据是私有的,要通过外部接口访问)
int getId(){return id;}
double getBanlance(){return balance;}
double getRate(){return rate;}
//存取现金
void deposit(int date,double amount); //存入现金
void withdraw(int date,double amount); //取出现金
//结算利息,每年1月1日调用一次该函数
void settle(int date);
//显示账户信息
void show();
};
//SavingsAccount类相关函数实现
//构造函数
SavingsAccount::SavingsAccount(int date,int id,double rate):id(id),balance(0),rate(rate),lastDate(date),accumulation(0)
{
cout<<date<<"\t#"<<id<<"is created"<<endl;
}
//计算一笔账
void SavingsAccount::record(int date,double amount)
{
//更新余额累积值
accumulation=accumulate(date);
//更新日期
lastDate=date;
//将输入数据保留小数点后两位
amount=floor(amount * 100 +0.5)/100;//保留小数点后两位
//将变动量加入余额
balance += amount;
//输出提示信息
cout<<date<<"\t#"<<id<<"\t"<<amount<<"\t"<<balance<<endl;
}
//存入现金
void SavingsAccount::deposit(int date,double amount)
{
record(date,amount);
}
//取出现金
void SavingsAccount::withdraw(int date,double amount)
{
if(amount>getBanlance())
cout<<"Error: not enough money"<<endl;
else
record(date,-amount);
}
//计算年利息
void SavingsAccount::settle(int date)
{
double interest=accumulate(date)*rate/365;
if(interest!=0)
record(date,interest);
accumulation=0;
}
//显示账户信息
void SavingsAccount::show()
{
cout<<"#"<<id<<"\tBalance:"<<balance;
cout<<endl;
}
int main()
{
//建立2个账户
SavingsAccount sa0(1,21325302,0.015);
SavingsAccount sa1(1,58320212,0.015);
//几笔账目
sa0.deposit(5,5000);
sa1.deposit(25,10000);
sa0.deposit(45,5500);
sa1.withdraw(60,4000);
//开户第90天到了银行计息日,结算所有账户的年息
sa0.settle(90);
sa1.settle(90);
//输出各个账户信息
sa0.show();
sa1.show();
getchar();//程序暂停
return 0;
}