目录概述友元普通的友元函数友元成员函数友元类总结概述 类的友元函数 (friend) 是定义在类外部, 但是有权限访问类的所有私有 (private) 成员和保护 (protecte
类的友元函数 (friend) 是定义在类外部, 但是有权限访问类的所有私有 (private) 成员和保护 (protected) 成员.
我们先来复习一下公有成员和私有成员的概念:
友元 (friend) 可以访问与其有好友关系的类中的私有成员 (有限制的共享).
友元包括友元函数和友元类:
Time 类:
#ifndef PROJECT2_TIME_H
#define PROJECT2_TIME_H
class Time {
private:
int hour;
int minute;
int second;
public:
Time();
Time(int, int, int);
friend void display(Time &); // display是Time类的friend函数
};
#endif //PROJECT2_TIME_H
Time.cpp:
#include <iOStream>
#include "Time.h"
using namespace std;
Time::Time() : hour(0), minute(0), second(0) {}
Time::Time(int h, int m, int s) : hour(h), minute(m), second(s) {}
void display(Time &t) {
// display不是Time类的成员函数, 但是可以引用Time中的私有成员
cout << t.hour << ":" << t.minute << ":" << t.second << endl;
}
main:
#include "Time.h"
#include <iostream>
using namespace std;
int main() {
Time t1(8, 8, 8);
display(t1);
return 0;
}
Time 类:
#ifndef PROJECT2_TIME_H
#define PROJECT2_TIME_H
class Date; // 对Date类进行提前引用声明
class Time {
private:
int hour;
int minute;
int second;
public:
Time();
Time(int, int, int);
void display(Date &d);
};
#endif //PROJECT2_TIME_H
Date 类:
#ifndef PROJECT2_DATE_H
#define PROJECT2_DATE_H
#include "Time.h"
class Date {
private:
int year, month, day;
public:
Date(int, int, int);
friend void Time::display(Date &d);
};
#endif //PROJECT2_DATE_H
Time.cpp:
#include <iostream>
#include "Time.h"
#include "Date.h"
using namespace std;
Time::Time() : hour(0), minute(0), second(0) {}
Time::Time(int h, int m, int s) : hour(h), minute(m), second(s) {}
void Time::display(Date &d) {
cout << d.year << "年" << d.month << "月" << d.day << "日" <<endl;
cout << hour << ":" << minute << ":" << second << endl;
}
main:
#include "Time.h"
#include "Date.h"
#include <iostream>
using namespace std;
int main() {
Time t1(8, 8, 8);
Date d1(2021, 5, 6);
t1.display(d1);
return 0;
}
输出结果:
2021年5月6日
8:8:8
我们可以发现 display 不是 Date 类的成员函数, 但是可以引用 Date 中的私有成员.
Time 类:
#ifndef PROJECT2_TIME_H
#define PROJECT2_TIME_H
class Date; // 对Date类进行提前引用声明
class Time {
private:
int hour;
int minute;
int second;
public:
Time();
Time(int, int, int);
void display(Date &d);
};
#endif //PROJECT2_TIME_H
Date 类:
#ifndef PROJECT2_DATE_H
#define PROJECT2_DATE_H
#include "Time.h"
class Date {
private:
int year, month, day;
public:
Date(int, int, int);
friend class Time; // 友元类
};
#endif //PROJECT2_DATE_H
友元的性质:
友元的优缺点:
我们在使用友元的时候, 应当时刻考虑友元的缺点. 如果能用公共成员函数解决就不必用友元.
到此这篇关于c++中友元的详解及其作用介绍的文章就介绍到这了,更多相关C++友元内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: C++中友元的详解及其作用介绍
本文链接: https://www.lsjlt.com/news/134848.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0