Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
Clark Lin
StudyCpp
Commits
e2de3e3f
Commit
e2de3e3f
authored
Nov 21, 2022
by
Clark Lin
Browse files
add friend function
parent
9c483d7e
Changes
1
Show whitespace changes
Inline
Side-by-side
02.OOP/FriendFunc.cpp
0 → 100644
View file @
e2de3e3f
#include <iostream>
using
namespace
std
;
class
Box
{
private:
double
width
;
public:
double
length
;
// 类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。
// 尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。
friend
void
printWidth
(
Box
box
)
{
// 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员
cout
<<
"Width of box : "
<<
box
.
width
<<
endl
;
};
void
setWidth
(
double
width
)
{
this
->
width
=
width
;
};
};
// 程序的主函数
int
main
()
{
Box
box
;
// 使用成员函数设置宽度
box
.
setWidth
(
10.0
);
// 使用友元函数输出宽度
printWidth
(
box
);
return
0
;
}
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment