当前位置:文档之家› 类和对象实验报告

类和对象实验报告

洛阳理工学院实验报告
};
Coordinate::Coordinate(Coordinate &p)
{ x=p.x;
y=p.y;
cout<<”copy-initialization Constructou is called\n”;
}
int main()
{ Coordinate p1(3,4);
Coordinate p2(p1);
Coordinate p3=p2;
cout<<”p3=(“<<p3.getx()<<”,”<<p3.gety()<<”)\n”;
return(0);
}
(1)程序运行结果
(2)将Coordinate类中带有两个参数的构造函数进行修改,在函数体内增添下述语句:
cout<<”Constructor is called.\n”;
写出程序的运行结果,并解释输出结果。

运行结果如下
解释输出结果:在编写的程序中有cout<<”copy-initialization Constructou is called\n”;执行主函数时,在主函数中定义对象p1,并传进两个参数,系统自动调用有两个参数的构造函数,给x,y赋值后执行cout语句输出Constructor is called.
(3)按下列要求进行调试:
在主函数体内,添加下列语句:
Coordinate p4;
Coordinata p5(2);
调试程序时会出现什么错误?为什么?如何对已有的构造函数进行适当修改?
③出现的错误:
int main()
{
Coordinate p1(3,4);
Coordinate p2(p1);
Coordinate p3=p2;
Coordinate p4;
Coordinate p5(2);
cout<<"姓名:王婷,学号:201140410340 "<<endl;
cout<<"p3=("<<p3.getx()<<","<<p3.gety()<<")\n";
cout<<"p4=("<<p4.getx()<<","<<p4.gety()<<")\n";
cout<<"p5=("<<p5.getx()<<","<<p5.gety()<<")\n";
return(0);
}
运行结果如下:
for(int i=0;i<4;i++)
{
m[i][i]=sum-m[i][i];
m[i][3-i]=sum-m[i][3-i];
}
}
void magic::printmagic()
{
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
cout<<m[i][j]<<"\t";
cout<<endl;
}
}
int main()
{
magic demo;
demo.getdate();
demo.setfirstmagic();
demo.generatemagic();
demo.printmagic();
return 0;
}
运行结果如下
②运行结果:
③结果分析:此代码定义了个Location类,求两点的距离,通过getx和gety方法获取类的私有成员即该点的坐标。

然后求出两点间的距离并输出。

4.声明一个Student类,在该类中包括一个数据成员score(分数)、两个静态数据成员total_score (总分)和count(学生人数);还包括一个成员函数account()用于设置分数、累计学生成绩之和、累计学生人数,一个静态成员函数sum()用于返回学生的成绩之和,另一个静态成员函数average ()用于求全班成绩的平均值。

在main函数中,输入某班同学的成绩,并调用上述函数求出全班学生的成绩之和和平均分。

程序如下:
#include<iostream>
using namespace std;
class Student{
private:
float score;
static int count;
static float total_score;
public:
void account(float score1) {score=score1;
++count;
total_score=total_score+score; }
static float sum()
{return total_score;
}
static float average()
{
return total_score/count;
}
};
int Student:: count=0;
float Student:: total_score=0.0;
int main()
{
Student s1,s2;
s1.account(99);
cout<<Student::sum()<<endl; cout<<Student::average()<<endl; s2.account(70);
cout<<Student::sum()<<endl; cout<<Student::average()<<endl; return 0;
}
输出结果如下:
5.使用C++的string类,将5个字符串按逆转后的顺序显示出来。

例如,逆转前的5个字符串是:
Germany Japan America Britain France
按逆转后的顺序输出字符串是:
France Britain America Japan Germany
解答如下
① 写源代码如下:
#include <iostream.h>
#include <math.h>
class Location {
public:
Location(double,double);
double Getx()
{
return x;
}
double Gety()
{
return y;
}
double distance(Location &);
②运行结果:
实验总结:
类的私有成员只能被内部方法访问,不能被对象访问,更不能被其他对象访问,但是可以利用友元函数可以访问。

每个类必须有无参数的默认构造函数,当没有定义构造函数时,系统会自动添加默认构造函数,否则,必须自己重新定义默认构造函数。

相关主题