当前位置:文档之家› 实验3 类的定义、对象的建立与使用

实验3 类的定义、对象的建立与使用

实验报告_实验3 类的定义、对象的建立与使用(学
生学号_姓名)
实验目的:
1、理解C++中class与struct的区别;
2、掌握类的定义以及成员函数的定义方法;
3、掌握对象的定义和对象成员的访问方式;
4、熟悉this指针的基本用法。

实验内容
二、((基础题)请按照下列要求定义一个Clock时钟类,并创建对象,再调用相应方法:
程序代码:
//日期类的应用
#include <iostream>
using namespace std;
class Clock // 定义日期类
{
public: // 定义公有成员函数
void setTime(int h, int m, int s);
void showTime();
private: // 定义私有数据成员
int hour;
int minute;
int second;
}; // 类定义体的结束
//类实现部分
void Clock::setTime(int h, int m, int s)
{
hour = h;
minute = m;
second = s;
}
void Clock::showTime()
{
cout << "设置时间为" << hour <<":"<< minute <<":"<< second << endl; }
int main()
{
Clock now;
now.setTime(8,30, 0);
now.showTime();
return 0;
}
三、(基础题)请按要求,编写程序(请将类的定义、成员函数的实现、类的使用分开):
rect.h代码:
#include<iostream>
using namespace std;
class Rect
{
public:
double getLength(void);
double getWidth(void);
double getPerimeter(void);
double getArea(void);
void setLength(double l);
void setWidth(double w);
void display(void);
private:
double length,width;
};
rect.cpp代码:
#include" rect.h"
void Rect::setLength(double l)
{
length=l;
}
void Rect::setWidth(double w)
{
width=w;
}
double Rect::getLength(){return length;}
double Rect::getWidth(){return width;}
double Rect::getArea(){return (length*width);}
double Rect::getPerimeter(){return (2*(length+width));}
void Rect::display()
{
cout<<length<<","<<width<<","<<length*width<<","<<2*(length+width); }
main函数代码:
#include" rect.h"
void main()
{
Rect myrect;
myrect.setLength(10.0);
myrect.setWidth(5.0);
cout<<"其长度、宽度、面积和周长:";
myrect.display();
}。

相关主题