当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 友元函数破坏信息隐藏性

友元函数破坏信息隐藏性

2019年04月09日  | 移动技术网IT编程  | 我要评论

快乐大本营20090221,偷逃上万元通行费,常州无痛人流多少钱

//
//  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

思考

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

参考文献

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网