- 25
- 0
- 约 9页
- 2016-04-12 发布于安徽
- 举报
友元函数与友元类的定义及使用.doc
C++实验报告
实验名称
友元函数和友元类的定义及使用
实验目的
理解对象与类的关系,掌握对象的创建和使用
掌握构造函数、析构函数的概念及使用方法
掌握内存的动态分配的概念和使用方法
掌握对象数组和对象指针
掌握函数调用中参数的传递
掌握友元函数和友元类的定义及使用
class 类名 {
private:
数据成员或成员函数
protected:
数据成员或成员函数
public:
数据成员或成员函数
};
实验内容
有Distance类和Point类,将Distance类定义为Point类的友元类来实现计算两点之间距离
实验代码
// point.h
class Distance;
class Point
{
public:
Point(int xx=0,int yy=0)
{
X=xx;
Y=yy;
}
friend class Distance;
private:
int X,Y;
};
class Distance
{
public:
float fDist(Point a,Point b);
};
//point.cpp
#includeiostream
#includemath.h
using namespace std;
#includepoint.h
#include math.h
int _tmain(int argc, _TCHAR* argv[])
{
Point myp1(1,1),myp2(4,5);
Distance d;
coutThe distance is: ;
coutd.fDist(myp1,myp2)endl;
return 0;
}
float Distance::fDist(Point p1,Point p2)
{
double x,y;
x=p1.X -p2.X ;
y=p1.Y -p2.Y ;
return float(sqrt(x*x+y*y));
}
心得体会
通过本次试验,让我更加熟练运用了友元函数和友元类的定义及使用,加快了学习的进程,知识的掌握
实验名称
运算符重载
实验目的
理解为什么要进行运算符重载,在什么情况下进行运算符重载。
掌握成员函数重载运算符。
掌握友元函数重载运算符。
理解并掌握引用在运算符重载中的作用。
理解类型转换的必要性,掌握类型转换的使用方法
实验内容
编写一个程序,用成员函数重载运算符“+”和“?”,实现两个二维数组相加和相减,要求第一个二维数组的值由构造函数设置,另一个二维数组的值由键盘输入。
实验代码
const int m=3;
const int n=4;
class Matrix // matrix.h
{
private:
int a[m][n];
public:
Matrix();
Matrix(int b[][n]);
Matrix operator +(Matrix b);
Matrix operator -(Matrix b);
void Print();
};
// matrix.cpp
#includeiostream
using namespace std;
#include matrix.h
int main( )
{
Matrix a,c;
int x[m][n];
int i,j;
coutinput Matrixendl;
for(i=0;im;i++)
for(j=0;jn;j++)
cinx[i][j];
Matrix b(x);
c=a+b;
coutendlc=a+bendl;
c.Print ();
c=a-b;
coutendlc=a-bendl;
c.Print ();
return 0;
}
Matrix::Matrix()
{
int i,j;
for (i=0;im;i++)
for(j=0;jn;j++)
a[i][j]=2;
}
Matrix::Matrix(int b[][n])
{
int i,j;
for (i=0;im;i++)
for(j=0;jn;j++)
a[i][j]=b[i][j];
}
Matrix Matrix::operator +(Matrix b)
{
Matrix c;
int i,j;
for (i=0;im;i++)
for(j=0;jn;j++)
c.a[i][j]=a[i][j]+b.a[i][j];
return c;
}
Matrix Matrix::operator -(Matrix
您可能关注的文档
最近下载
- 浙江省台风年鉴(原始资料).doc VIP
- 《光电图像处理》第五章图像变换及应用.ppt VIP
- 新源县肖尔布拉克镇C波段双偏振天气雷达建设项目环评(新版环评)环境影响报告表.pdf
- 2025年贵州高考物理含解析及答案.docx VIP
- 2025年高考英语一轮复习精品讲义—必修第二册:Unit 2 Let’s celebrate(外研版).pdf VIP
- XR360旋挖钻机技术规格书(修订).docx
- 2025年高考英语一轮复习精品讲义—必修第二册:Unit 3 On the move(外研版).pdf VIP
- 宿迁市2026届高三(一模)英语试卷(含答案).docx
- 2026年10篇稿:领导班子“五个带头”方面在带头强化政治忠诚、提高政治能力等对照检查材料【供参考】.docx VIP
- 2023年青岛城市学院数据科学与大数据技术专业《数据结构与算法》科目期末试卷A(有答案).docx VIP
原创力文档

文档评论(0)