码迷,mamicode.com
首页 > 其他好文 > 详细

关于友元函数 函数初始化

时间:2016-05-06 19:02:40      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

例题:定义一个继承与派生关系的类体系,在派生类中访问基类成员。先定义一个点类,包含x,y坐标数据成员,显示函数和计算面积的函数成员;以点为基类派生一个圆类,增加表示半径的数据成员,重载显示和计算面积的函数;定义一个线段类,以两个点类对象作数据成员,定义显示、求面积及长度函数,线段类采用聚合方式,因为有两个端点,不能用派生

下面的注释为注意事项

#include<iostream> #include<cmath> using namespace std; const float PI = 3.14; class Point { private: double x, y ; int area; public: Point(int x, int y) { this->x = x; //这里需要注意 必须用this关键字 否则无法为x赋值 this->y = y; }; float Area() { return area; } friend class Line; }; class Circle :public Point { private: float r; public: Circle(int x, int y, float r) :Point(x, y) { //注意这里面的数据初始化 典型例子 this->r = r; } float area() { cout << r*r*PI; return 0; } }; class Line { private: Point A, B; public: Line() :A(0, 0), B(0, 0) { } Line(int a, int b, int c, int d) :A(a, b), B(c, d) { } int Long() { cout << endl;

//这里需要注意 A是Line类中的对象 但是是由Point类拓展来的 所以应该用A.x(Point类中的变量) cout << sqrt((A.x-B.x)*(A.x-B.y)+(A.y-B.y)*(A.y-B.y)); return 0; } }; int main() { Circle c(0, 0, 2); c.area(); Line point(5,5,9,6); point.Long(); return 0; }

关于友元函数 函数初始化

标签:

原文地址:http://www.cnblogs.com/lnzhangsong/p/5466359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!