派生类的友元函数
来源:互联网 发布:数据中心网络架构 编辑:程序博客网 时间:2024/06/05 20:03
派生类的友元函数
#include "stdafx.h"#include <iostream>using namespace std;#if 0由于友元函数并非类成员,因引不能被继承,在某种需求下,可能希望派生类的友元函数能够使用基类中的友元函数。为此可以通过强制类型转换,将派生类的指针或是引用强转为其类的引用或是指针,然后使用转换后的引用或是指针来调用基类中的友元函数。#endifclass Student{public:Student(int a, int b) :_a(a), _b(b){}friend ostream &operator<<(ostream & out, Student & stu);private:int _a;int _b;};ostream &operator<<(ostream & out, Student & stu){out << stu._a << "--" << stu._b << endl;return out;}class Graduate :public Student{public:Graduate(int a, int b, int c) :Student(a, b), _c(c){}friend ostream &operator<<(ostream & out, Graduate & gra);private:int _c;};ostream &operator<<(ostream & out, Graduate & gra){cout << static_cast<Student&>(gra); //友元函数不能被继承,需要转化为父类类型,然后调用其中的友元函数//如果不强制转化的话 参数匹配的函数还是它自己产生递归 系统崩溃cout <<"--"<< gra._c; return out;}int _tmain(int argc, _TCHAR* argv[]){Student s(1,2);cout << s ;Graduate g(3, 4, 5); //没有自己的<<重载函数时 赋值兼容 g赋值给了Student & st //赋给了父类的类型 所以才能访问父类的私有成员cout << g ;return 0;}
阅读全文
0 0
- 派生类的友元函数
- C++之派生类的友元
- c++之派生类访问基类的友元函数
- 友元关系与继承以及基类派生类定义构造函数时应该注意的事项
- C++基础-友元函数和继承派生
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- Activiti 工作流 流程各个步骤所涉及到的表 05
- JavaSE,JavaWeb,框架书籍分享
- 最基础的“穷竭搜索”(递归)
- QT控件大全 二十 QSlideplug
- Andorid Studio项目上传到Coding流程
- 派生类的友元函数
- 银行家算法
- 精妙SQL语句
- kafka性能监控之KafkaMetrics Sensor
- vs秘钥
- opencv 实现PNG的透明背景
- 记录两个官方的ViewPager动画
- 查看import的类是出自哪个jar包的方法
- 2017.12.8