友元类和友元函数


全局函数
成员函数
友元函数
友元全局函数
class Coordinate
{
    friend void printXY(Coordinate &c);//通常友元函数写在一个类的开头
public:
    Coordinate(int x,int y);
private:
    int m_ix;
    int m_iy;
};

void printXY(Coordinate &c)//这里传入一个引用或者指针传递效率更高,执行速度更快
{
    cout<<c.m_ix<<c.m_iy;
}
int main()
{
    Coordinate coor(3,5);
    printXY(coor);//传入对象名
    return 0;
} 

友元的注意事项:
    1、友元关系不可传递 
    2、友元关系的单向性
    3、友元声明的形式及数量不受限制
    4、友元破坏了数据的封装性
    
    

//Time 类
#ifdef TIME_H
#define TIME_H

class Match;//声明类
class Time
{
    friend Match;//友元类
public:
    Time(int hour,int min,int sec);
private:
    void printTime();
    int m_iHour;
    int m_iMin;
    int m_iSec;
};

#endif

#include"Match.h"
#include<iostream>
using namespace std;
Match::Match(int hour,int min,int sec):m_tTimer(hour,min,sec)
{
    
    
}
void Match::testTime()
{
    m_tTimer.printTime();
    cout<<m_tTimer.m_iHour<<":"
        <<m_tTimer.m_iMin<<":"
        <<m_tTimer.m_iSec<<;
    
}


#include "Time.h"
#include "Match.h"
#include "stdlib"
#include <iostream>
using namespace std;
main()
{
    Match m(6,30,55)
    
    
    
    system("puase");
    return 0;
}

class Tank
{
    public:
    Tank(){s_iCount++;}
    ~Tank(){s_iCount--;}
    static int getCount(){return s_iCount;}//静态成员函数
    //静态函数能调用静态的数据成员。而不能调用非静态的数据成员和非静态的成员函数,因为this指针找不到。
    //成员函数可以调用静态成员函数
    static int s_iCount;   //静态数据成员
private:

    string m_strCode;
};
int Tank::s_iCount=0;
普通的数据成员与静态的数据成员的区别:

静态的数据成员和静态的成员函数都是随类的产生而产生,只有一份是依赖于类存在的
而普通的数据成员是依赖于对象存在的
静态成员函数不会传入一个this指针
静态数据成员必须单独初始化

int main()
{
    cout<<Tank::getCount()<<endl;
    count<<Tank::s_iCount<<endl;
    Tank t1;
    cout<<t1.getCount()<<endl;
    cout<<t1.s_iCount<<endl;
    return 0;
}



#include <iostream>
using namespace std;
class Watch;

/**
 * 定义Time类
 * 数据成员:m_iHour, m_iMinute,m_iSecond 
 * 成员函数:构造函数
 * 友元类:Watch
 */
class Time
{
    // 友元类
    friend Watch;
public:
    Time(int hour, int min, int sec)
    {
        m_iHour = hour;
        m_iMinute = min;
        m_iSecond = sec;
    }
public:
    int m_iHour;
    int m_iMinute;
    int m_iSecond;
};

/**
 * 定义Watch类
 * 数据成员:m_tTime
 * 成员函数:构造函数
 * display用于显示时间
 */
class Watch
{
public:
     Watch(Time &m_tTime):m_tTime(m_tTime){};
    void display()
    {
        cout << m_tTime.m_iHour << endl;
        cout << m_tTime.m_iMinute << endl;
        cout << m_tTime.m_iSecond << endl;
    }
public:
    Time m_tTime;
};

int main()
{
    Time t(6, 30, 20);
    Watch w(t);
    w.display();

    return 0;
}

猜你喜欢

转载自blog.csdn.net/usstmiracle/article/details/83090288