关于友元函数 函数初始化
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; }
下面的注释为注意事项
#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; }
相关文章推荐
- CSS预处理器Sass、LESS 和 Stylus
- mavan和idea的搭建,很好的一篇文章
- GrepCode
- MySQL 主从同步设置
- Jquery获得控件值的三种方法总结
- android textview 自动换行 整齐排版
- 关于Linux系统的swap交换空间
- Block传值解析
- 支付宝-即时到账交易接口
- 进程快速定位
- hdu1181变形课
- More Effective C++----(18)分期摊还期望的计算
- Anniversary party(树形dp第一步)
- 合并果子
- Block传值解析
- iOS 网络编程之TCP/IP <四> 根据协议解析数据
- 网站添加数据出错,原来是MS SQL Server2008日志文件占据空间过大导致的
- 微软下载http://www.itellyou.cn/,系统、MSDN等
- Spring4 集成 Hibernate3 使用 HibernateTemplate 和使用 HibernateDaoSupport 操作对象
- iOS实现表格(非TableView)