友元函数破坏信息隐藏性

mac2022-06-30  20

// // main.cpp // friendFunction // 1. 静态成员变量需要在类中声明,在类外定义。 // 2. 友元函数相当于成员函数,可以访问私有变量,破坏信息的隐藏性。 // 3. 模版类的的静态成员变量的定义与声明。 // Created by mac on 2019/4/8. // Copyright © 2019年 mac. All rights reserved. // #include <iostream> using namespace std; //模版类中嵌套模版函数 //模版类 template <class genType> class genClass { public: genClass(genType a){ n=a; } ~genClass(){} //模版函数 template <class gentype> gentype f(genType n){ return n; }; friend int g();//友元函数 private: static genType n;//静态成员变量 默认初始化为0 double a=1.5; }; template <class genType>genType genClass<genType>::n; int g(){ return genClass<int>::n; } int main(int argc, const char * argv[]) { genClass<int> object1(3),*p=&object1; cout<<p->f<int>(3)<<endl; cout<<g()<<endl; return 0; }

Tips

静态成员变量需要在类外进行定义标准模板库(Standard Template Library,STL),这个库包括三种类型的通用项:容器、迭代器和算法。STL包括的容器有:deque、list、map、multimap、set、multimap、set、multiset、stack、queue、priority_queue、vector

思考

怎么理解变量的声明跟定义之间的关系?

参考文献

[https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.2.0/com.ibm.zos.v2r2.cbclx01/static_data_members_and_templ.htm]

转载于:https://www.cnblogs.com/overlows/p/10672263.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)