提交 c19dd8fa 编写于 作者: W wsb

增加友元函数的使用示例!

上级 b58f3bd1
......@@ -3,4 +3,4 @@ project(cpp_10_defineClass)
set(CMAKE_CXX_STANDARD 11)
add_executable(cpp_10_defineClass main.cpp Student.cpp Student.h Book.cpp Book.h)
add_executable(cpp_10_defineClass main.cpp Student.cpp Student.h Book.cpp Book.h friendFunc.cpp friendFunc.h)
//
// Created by 11010 on 2023/4/8.
//
#include "friendFunc.h"
//定义友元函数: 可以看到,被private修饰的成员均可访问
void printInfo(friendFunc f) {
cout<<f.name<<"信息为:"<<","<<f.age<<","<<f.hobby<<","<<endl;
}
void friendFunc::setHobby(string hobby)
{
this->hobby=hobby;
}
//
// Created by 11010 on 2023/4/8.
//
#ifndef CPP_10_DEFINECLASS_FRIENDFUNC_H
#define CPP_10_DEFINECLASS_FRIENDFUNC_H
#include <iostream>
#include <string>
using namespace std;
//申明一个类
class friendFunc {
//写一些属性
public:
string name;
int age;
//使用friend关键字申明友元函数: 友元函数不属于任何类,仅仅是可以访问friendFunc的任何成员
friend void printInfo(friendFunc f);
void setHobby(string hobby);
private:
string hobby;
};
#endif //CPP_10_DEFINECLASS_FRIENDFUNC_H
#include <iostream>
#include "Student.h" //在使用自定义类之前,需要导入对应的头文件
#include "Book.h"
#include "friendFunc.h"
int main() {
......@@ -35,5 +36,13 @@ int main() {
book.disValue(book);
//给类成员赋值
friendFunc friendFunc;
friendFunc.name="friendFunc";
friendFunc.age=35;
friendFunc.setHobby("打羽毛球"); //若是普通的访问方式,需要使用set方法来访问被private修饰的变量
//使用友元函数访问类的任意成员
printInfo(friendFunc);
return 0;
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册