友元类

  • 头文件
//mytest.h
#ifndef MYTEST_H_INCLUDED
#define MYTEST_H_INCLUDED

#include <iostream>

class Student2;//注意:这里必须加上Student2的前向声明,不然会报错

class Student1
{
private:
    friend class Student2;
    std::string m_name;
    int m_age;
    float m_height;
    int m_score;
public:

    Student1():m_name("Student1"), m_age(24), m_height(167.5), m_score(85) {}
    void GetFriend(Student2 &);
    void ShowInfomation();
};

class Student2
{
private:
    friend class Student1;
    std::string m_name;
    int m_age;
    float m_height;
    int m_score;
public:
    Student2():m_name("Student2"), m_age(25), m_height(175.5), m_score(90) {}
    void GetFriend(Student1 &);
    void ShowInfomation();
};

inline void Student1::GetFriend(Student2 & stu)
{
    std::cout << m_name << "\'s good friend is:" << stu.m_name << std::endl;
    std::cout << stu.m_name << "\'s information:\n\t\t\t";
    stu.ShowInfomation();
}

//内联函数的连接性是内部的,这意味着函数定义必须在使用函数的文件中,
//所以将内联函数和模板放在同一个文件中,再包含进主程序文件
inline void Student1::ShowInfomation()
{
    std::cout << "age:" << m_age << "\n\t\t\t"
              << "height:" << m_height << "\n\t\t\t"
              << "score:" << m_score << std::endl;
}

inline void Student2::GetFriend(Student1 & stu)
{
    std::cout << m_name << "\'s good friend is:" << stu.m_name << std::endl;
    std::cout << stu.m_name << "\'s information:\n\t\t\t";
    stu.ShowInfomation();
}

inline void Student2::ShowInfomation()
{
    std::cout << "age:" << m_age << "\n\t\t\t"
              << "height:" << m_height << "\n\t\t\t"
              << "score:" << m_score << std::endl;
}

#endif // MYTEST_H_INCLUDED
  • 主程序文件
//main.cpp
#include "mytest.h"

int main()
{
    Student1 stu1;
    Student2 stu2;
    stu2.GetFriend(stu1);
    stu1.GetFriend(stu2);

    return 0;
}
  • 执行结果:
    这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值