第19章:special operators
来源:互联网 发布:java ee创建web项目 编辑:程序博客网 时间:2024/05/16 00:24
友元
1:友元概念及用处
2:友元声明:
(1):类的成员函数作为友元:
namespace ex{class A; //类A的前向声明;class B{public: int f(const A&);};class A{ friend int B::f(const A&);private: int a;};/*int B::f(const A& x){ return x.a;}*/}int ex::B::f(const A& x){ return x.a;}
(2):当我们想要在类A中将整个类B或普通的非成员函数f()设为友元时,我们没必要在类A定义之前声明类B或普通函数f()。我们可以在类A定义之后定义类B或普通函数f(),但是类B或普通函数f()定义所在的作用域应该是包围了类A的最内层的作用域,否则不能调用类A的私有成员。例子代码如下:
namespace ex{class A{ friend class B; friend int f(const A&);private: int a;};//Okay!class B{public: int val(const A& x) { return x.a;}};inline int f(const A& x){ return x.a;}}//error!class B{public: int val(const ex::A& x) { return x.a;}};inline int f(const ex::A& x){ return x.a;}
3:友元与类继承
4:类模板中的友元声明
1:普通非模板类或函数的友元声明,将友元关系授予明确指定的类或函数;2:类模板或函数模板的友元声明,授予对友元所有实例的访问权;3:只授予对类模板或函数模板的特定实例的访问权的友元声明。
(1):普通友元:
template<class Type>class Bar{friend class FooBar;friend void fcn();};
(2):一般模板友元关系
template<class Type>class Bar{template<class T> friend class Foo1;template<class T> friend void temp1_fcn1(const T&);}
(3):特定的模板友元关系:
template<class T>class Foo2;template<class T>void temp1_fcn2(const T&);template<class Type>class Bar{friend class Foo2<char*>;friend void temp1_fcn2<char*>(char* const&);};
即使Foo2本身是类模板,友元关系也只能拓展到Foo2的形参类型为char*的特定实例。类似地,temp1_fcn2的友元声明是说,只有形参类型为char*的函数实例是Bar类的友元。形参类型为char*的Foo2和temp1_fcn2的特定实例都可以访问Bar的每个实例。
下面形式的友元声明更为常见:
template<class T>class Foo3;template<class T>void temp1_fcn3(const T&);template<class Type>class Bar{friend class Foo3<Type>;friend void temp1_fcn3<Type>(const Type&);};
Foo3<int>
可以访问Bar<int>
的私有部分,但不能访问Bar<string>
或者任意其他Bar实例的私有部分。
(4):声明依赖性:
template<class T> class A;template<class T> class B{friend class A<T>; //ok: A is known to be a template.friend class C; //ok: C must be an ordinary nontemplate class;template<class S>friend class D; //ok: D is a templatefriend class E<T>; //error:E wasn't declared as a template;friend class F<int>; // F wasn't declared as a template};
- 第19章:special operators
- Operators and special characters in matlab
- Operators
- Operators
- Operators
- Operators
- mysql官方文档阅读笔记(四)Chapter 13 Functions and Operators第13章-函数和运算符
- Java程序设计(Java9版):第2章 数据类型与运算符(Data types and Operators)
- 《The C++ Programming Language, special edition》第6章6.6节中的一道有趣习题ch6.6-15
- 《JAVA编程思想》学习备忘(第93页:Operators--1)
- 《JAVA编程思想》学习备忘(第93页:Operators--2)
- 《JAVA编程思想》学习备忘(第93页:Operators--3)
- XPath Operators
- 14.2 Operators
- 17.9 Operators
- Oracle Operators
- Conversion Operators
- C++ Operators
- 51nod 1283 最小周长
- BZOJ 1670 [Usaco2006 Oct]Building the Moat护城河的挖掘
- 第15周实践项目1——程序填空
- 解决Linux连不上外国软件源或者软件源失效
- Codeforces #1 A
- 第19章:special operators
- 学习整理01-java将汉字转换为拼音
- Android开源框架——依赖注入Dagger
- Linux cp命令处理 普通文件 隐藏文件 普通目录 隐藏目录
- TopCoder SRM 637 Div2 A
- Qt/C++ 波形图 心电波 实时显示
- 十步完全理解 SQL
- 八大排序算法
- redis学习笔记——主从同步(复制)