抱歉,上面的回答确实不够完整,让我们重新整理下代码逻辑。问题的根源在于您试图在`Building`类中引用`Person`类的`getRoom`方法,但此时`Person`类尚未完整声明。这需要将友元声明移到`Building`类外,也就是在`Person`类中定义后再声明。在此情况下,友元函数应该先被完全定义后才能在别的类中被声明为友元。下面是修正后的代码:
- #include <iostream>
- #include <string>
- using namespace std;
- class Building
- {
- public:
- string sittingRoom;
-
- Building()
- {
- bedRoom = "卧室";
- sittingRoom = "客厅";
- }
- private:
- string bedRoom;
- // 让 Person 成为这个类的友元,以便其成员函数 getRoom 可以访问私有成员
- friend class Person;
- };
- class Person
- {
- public:
- Building* building;
- Person()
- {
- building = new Building;
- }
- void getRoom()
- {
- cout << "访问: " << building->sittingRoom << endl;
- // 访问Building的私有成员bedRoom
- cout << "访问: " << building->bedRoom << endl;
- }
- };
- int main()
- {
- Person person;
- person.getRoom();
-
- return 0;
- }
复制代码
在这个调整中,`Building`类的朋友改为整个`Person`类,这样`Person`类中的全部方法都能访问`Building`类的私有成员。请确保友元类或函数被提交完全定义后再被其访问目标的类声明。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。