C++笔记之全局函数做友元与类做友元
code review!
文章目录
- C++笔记之全局函数做友元与类做友元
- 1.全局函数做友元
- 2.类作友元
1.全局函数做友元
代码
#include <iostream>
using namespace std;class MyClass {
private:int x;
public:MyClass(int a) : x(a) {}friend void printX(MyClass obj);
};void printX(MyClass obj) {cout << "The private member x of MyClass is: " << obj.x << endl;
}int main() {MyClass obj(10);printX(obj);return 0;
}
2.类作友元
代码
class B;class A {
private:int a;
public:friend class B; // 声明B为A的友元类
};class B {
public:void func(A &obj) {obj.a = 10; // 可以访问A类的私有成员a}
};