C++类与对象实验报告.doc
文本预览下载声明
Guangxi University of Science and Technology
实验报告
实验课程: C++程序设计教程
实验内容: 类与对象
院 (系):
专 业:
班 级:
学生姓名:
学 号:
指导教师:
2013年 月日
实验题目二:
定义图书类。设图书信息包括书名、作者、出版社和定价属性,要求定义一
个类,用该类定义图书对象、通过函数成员为对象数据赋值、能输出图书属性。
要点分析:
对类进行初始化赋值,则需要用构造函数
程序源代码:
#include iostream
using namespace std;
#include string.h
class Book
{
public:
Book (char *bname,char *btutor,char *bchubanshe,int bprice)
{
strcpy(name,bname);
strcpy(tutor,btutor);
strcpy(chubanshe,bchubanshe);
price=bprice;
coutthe book information :;
coutname/tutor/chubanshe/priceendl;
}
Book (Book s)
{
cout.....endl;
}
~Book()
{
cout”析构函数endl;
}
private:
char name[20];
char tutor[20];
char chubanshe[20];
int price;
};
class abc
{
public:
abc(char *bname=noname,char *btutor=notutor,char *bchubanshe=nohourse,
int bprice=0):book(bname,btutor,bchubanshe,bprice)
{
coutconstucting abcendl;
}
protected:
Book book;
};
void fn()
{
coutthe last finallyendl;
}
void main()
{
abc(c++,阳树洪,清华大学出版社,42);
fn();
}
实验结果
(三)实验题目三: 定义一个类,输入若干学生的学号,姓名和成绩,然后显示这个数据并计算出平均分。同时设计出相应的程序进行测试。
程序源代码:
#include iostream
using namespace std;
#include string.h
class student
{
public:
student(char* sname,int sID,int sgoal) //构造函数
{
strcpy(name,sname);
name[sizeof(name)-1]=\0;
studentID=sID;
goal=sgoal;
coutname studentID goalendl;
}
private:
char name[20];
int studentID;
int goal;
};
void main()
{
char sname[10];
int sID;
int sgoal;
int n,avear;
int allsgoal=0;
coutplease input the total num :endl;
cinn;
for(int i=1;i=n;i++)
{
cinsname;
cinsID;
cinsgoal;
student a(sname,sID,sgoal);
allsgoal+=sgoal;
}
avear=allsgoal/n;
}
2.实验结果
(四)实验题目四: 声明一个通讯录类,含姓名、地址、电话号码成员数据,其中姓名和电话号 码使用字符数组,地址使用字符型指针成员。要求如下成员函数:构造函数、拷
贝构造函数、析构函数、输出所有成员的函数。main()完成对象的定义和有关成
员函数的测试。
2.程序源代码:
#include iostream
using namespace std;
#include string
显示全部