您的位置:首页 > 其它

关于友元函数 函数初始化

2016-05-06 17:10 218 查看
例题:定义一个继承与派生关系的类体系,在派生类中访问基类成员。先定义一个点类,包含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; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: