#include<iostream>
#include<string>
using namespace std;
class Bulding
{
friend void Goodgay::visit();
public:
Bulding()
{
m_room = "正在访问客厅";
b_room = "正在访问卧室";
}
string m_room;
private:
string b_room;
};
class Goodgay
{
public:
Goodgay();
void visit();
Bulding* bulding;
};
Goodgay::Goodgay()
{
bulding = new Bulding;
}
void Goodgay::visit()
{
cout << bulding->m_room << endl;
cout << bulding->b_room << endl;//显示不可访问
}
void test()
{
Goodgay b;
b.visit();
}
int main()
{
test();
return 0;
}
C++ 类A的成员函数作类B的友元函数,怎么访问不了类B的私有成员?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
qfl_sdu 2021-07-27 22:39关注在friend void Goodgay::visit();这里的时候,编译器不识别Goodgay,所以报错,代码修改如下:
如有帮助,请采纳一下,谢谢。#include<iostream> #include<string> using namespace std; class Bulding; class Goodgay { public: Goodgay(); void visit(); Bulding* bulding; }; class Bulding { friend void Goodgay::visit(); public: Bulding() { m_room = "正在访问客厅"; b_room = "正在访问卧室"; } string m_room; private: string b_room; }; Goodgay::Goodgay() { bulding = new Bulding; } void Goodgay::visit() { cout << bulding->m_room << endl; cout << bulding->b_room << endl;//显示不可访问 } void test() { Goodgay b; b.visit(); } int main() { test(); return 0; }本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 1无用