zoukankan      html  css  js  c++  java
  • C++友元函数和友元类

      通过友元,一个不同函数或另一个类中的成员函数可以访问类中的私有成员和保护成员

      friend void fun()和friend class A

    一、友元函数

      友元函数可以直接访问类的私有成员,但不能访问成员函数

     1 #include<iostream>
     2 
     3 using namespace std;
     4 
     5 class Interent;            //友元函数的参数
     6 void show(Interent& obj);//友元函数最好在类的外面也声明一下
     7 
     8 class Interent()
     9 {
    10 public:
    11     Interent(char*name, char* address):
    12         m_name(name),
    13         m_address(address){};
    14     friend void show(Interent &obj);
    15 private:
    16     char* m_name;
    17     char* m_address;    
    18 }
    19 
    20 void show(Interent &obj)//友元函数
    21 {
    22     cout<<obj.m_name<<endl;
    23     cout<<obj.m_address<<endl;
    24 }
    25 
    26 void main()
    27 {
    28     Interent i("wang","jiangsu");
    29     show(i);        //函数声明和定义的时候引用类型,使用时直接传对象
    30     system("pause");
    31 }

    二、友元类

       友元类的所有成员函数都是另一个类的友元函数。

    三、注意
      1)友元关系不能被继承。
      2)友元关系是单向的,不具有交换性
      3)友元关系不具有传递性。

  • 相关阅读:
    codevs2034 01串2
    codevs2622数字序列( 连续子序列最大和O(n)算法)
    codevs3008加工生产调度(Johnson算法)
    codevs1955光纤通信(并查集)
    codevs4203山区建小学
    codevs2618核电站问题
    常用端口
    ntp时间同步服务器
    date linux系统校正时间
    用户切换
  • 原文地址:https://www.cnblogs.com/wangbin-heng/p/9557125.html
Copyright © 2011-2022 走看看