c++程序设计实验报告

发布时间 : 星期二 文章c++程序设计实验报告更新完毕开始阅读

实验报告七 类与对象

1.实验目的

(1) 掌握类的定义和实现。

(2) 掌握对象创建及使用的基本方法。

2.实验设备

硬件环境:微型计算机 软件环境:

操作系统: Windows

语言环境: Visual C++

3.实验内容

(1)下面程序定义了一个以hours, minutes和seconds作为数据成员的Time类。设计了成员函数将两个Time对象相加(即时间相加),并进行相应的检查,查看增加的分钟数及秒数是否大于59。如果秒数大于59,则分钟数向前递增1。类似地,如果分钟数大于59,则小时数向前增1。

#include

class Time {

private: int hours, minutes, seconds; public: void get_time() { cin>>hours>>minutes>>seconds; } void display_time() { cout<=60) {

seconds-=60; minutes++; } if(minutes>=60) { minutes-=60; hours++; } } };

void main() { Time one, two, three; cout<<\ one.get_time(); cout<<\ two.get_time(); three.add_time(one,two); cout<<\ three.display_time(); }

[基本要求]

? 上机录入、调试上面程序。 ? 运行程序,输入下面两组数据: ① 2 34 45

1 47 56

② 2 67 100 1 56 200 分析运行结果是否正确。 [分析与思考]

? 定义构造函数对Time类的对象进行初始化(即不用成员函数get_time)。

? 该程序要求用户输入的分钟数和秒数必须小于60,如何修改程序使得用户在输入分钟数和秒数大于等于60时,也能得到正确的结果。

(2)阅读下面的一段程序代码,代码可能有错误,请仔细分析并体会。 class Date { public:

void Date(){};

int Date(int year,int month,int day); void ~Date(){};

int &GetYear(){return year;} int &GetMonth(){return month;}

int &GetDay(){return day;} private:

int year=2000; int month=12; int day=31;

static bool IsLeapyear;//是否闰年 };

bool Date::IsLeapyear=true;

int Date::Date(int year,int month,int day) {

(*this).year=year; (*this).month=month; (*this).day=day; }

void main() {

int year,month,day;

cin>>year>>month>>day; Date mydate(year,month,day); int &myyear=mydate.GetYear(); int &mymonth=mydate.GetMonth(); int &myday=mydate.GetDay();

cout<

cout<< mydate.GetYear(); }

[基本要求]

·仔细阅读上面程序,如果有错误,请更正。 ·上机录入、调试上面程序。 [分析和思考]

main函数中int &myyear=mydate.GetYear(); 、int &mymonth=mydate.GetMonth(); 和int &myday=mydate.GetDay();语句表达的是什么思想?这样做的目的是什么?这种方法是否“好”呢?为什么?如果“不好”应该怎样修改?

4.源代码

1.#include

class Time { private: int hours, minutes, seconds;

public: Time (){}

Time (int x,int y,int z){hours=x;minutes=y;seconds=z;} /* void get_time() { cin>>hours>>minutes>>seconds; }*/ void display_time() { cout<=60) { seconds-=60; minutes++; } while(minutes>=60) { minutes-=60; hours++; } } };

void main() {

Time one( 2 , 67 , 100), two( 1 , 56 , 200), three; three.add_time(one,two); cout<<\ three.display_time(); }

2.

#include class Date { public:

Date(){};

联系合同范文客服:xxxxx#qq.com(#替换为@)