友元函数与友元类的定义及使用.docVIP

  • 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

文档评论(0)

1亿VIP精品文档

相关文档