C++实验五
实验五 类与对象(一)
【实验目的】
1、掌握类的概念以及定义类的方法;
2、学习简单面向对象程序的编写;
【实验内容】
1、 设计一个名为Fan的类,表示一个风扇,该类满足下述要求:
•具有描述风扇转速的成员speed;
•具有描述风扇是否开启的成员on;
•具有描述风扇半径的成员radius;
•具有描述风扇颜色的成员color
•以上所有成员的访问和更改函数;
•输出风扇所有信息的函数display;
•在main函数中创建2个Fan的对象,将第一个风扇的转速、半径和颜色分别设置为3、10和yellow,并将它打开。第二个风扇的转速、半径和颜色分别设置为2、5和blue,并将它关闭。输出以上2个风扇的所有信息。
2、 设计一个名为Account的类,该类满足下述要求:
•一个名为id的int型成员,表示账户的身份号;
•一个名为balance的double型成员,表示账户余额;
•一个名为annualInterestRate的double型数据域,保存当年利率;
•以上所有成员的访问和更改函数;
•一个名为getMonthlyInterestRate( )的函数,返回月利率;月利率为年利率/12;
•一个名为withDraw的函数,从账户中支取指定金额;
•一个名为deposit的函数,向账户中存入指定金额;
•在mian函数中,创建一个Account对象,其ID为1122,账户余额为20000,年利率为4.5%,使用withDraw函数取出2500美元,使用deposit函数存入3000美元,然后输出账户的余额、月利率。
【实验要求】
1、编写实验内容要求的程序、编译并调试通过;
2、实验报告中记录编程过程中出现的错误与改正方法;
3、在报告中回答以下问题:
•定义类时,那些成员数据和成员函数是必须的,那些不是?public、protected、private分别表示什么意思?能否对类的成员数据在定义时初始化?
•在实验内容的第2小题中,账户余额变量balance是否必须定义为静态变量?为什么?
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 class Fan 5 {public: 6 Fan(float s,float r,string c,string p){ speed=s;radius=r;color=c;zt=p;} 7 void display() { cout<<"speed:"<<speed<<" radius:"<<radius<<" color:"<<color<<" condition:"<<zt<<endl;} 8 private: 9 float speed; 10 float radius; 11 string color; 12 string zt; 13 }; 14 int main(){ 15 Fan fan1(3,10,"yellow","on"); 16 fan1.display(); 17 Fan fan2(2,5,"blue","off"); 18 fan2.display(); 19 return 0; 20 }
1 #include<iostream> 2 using namespace std; 3 class Account 4 {public: 5 Account(int i,double b,double a){ id=i;balance=b;annualInterestRate=a;} 6 double getMonthlyInterestRate( ) { return annualInterestRate/12;} 7 void withDraw(double cut){ balance-=cut;} 8 void deposit(double add){balance+=add;} 9 double out(){ return balance;} 10 private: 11 int id; 12 double balance; 13 double annualInterestRate;//数据域 14 }; 15 int main(){ 16 Account account(1122,20000,0.045); 17 account.withDraw(2500); 18 account.deposit(3000); 19 cout<<"the last balance:"<<account.out()<<"\nmonthlyInterestRate:"<<account.getMonthlyInterestRate()<<endl; 20 return 0; 21 }