|
|
发表于 2025-3-8 17:14:40
|
显示全部楼层
在您的代码中,您尝试将 `getRoom` 函数设为 `Building` 类的友元函数,但由于 `Person` 类在 `Building` 类之后才定义,因此无法在 `Building` 类中声明 `Person::getRoom()` 为友元函数。这是因为编译器在定义 `Building` 类时尚未知道 `Person::getRoom()` 函数的存在。
为了解决这个问题,您可以将 `Person` 类的定义移到 `Building` 之前,或者将友元声明的地方调整一下。这里有一个可能的解决方案:
- #include <iostream>
- #include <string>
- using namespace std;
- class Person; // 提前声明 Person 类
- class Building
- {
- friend void Person::getRoom(); // 让 Person::getRoom() 成为 Building 类的友元
- public:
- Building()
- {
- bedRoom = "卧室";
- sittingRoom = "客厅";
- }
- string sittingRoom;
- private:
- string bedRoom;
- };
- class Person
- {
- public:
- Building* building;
- Person()
- {
- building = new Building;
- }
- void getRoom()
- {
- cout << building->bedRoom << endl; // 访问私有成员 bedRoom
- }
- };
- int main()
- {
- Person p;
- p.getRoom();
- return 0;
- }
复制代码
通过提前声明 `Person` 类,并在 `Building` 类中正确地引用 `Person::getRoom()`,可以解决您面临的问题。请注意,使用 `backcolor=#eee` 来表示行内代码时,需要根据您的环境调整。希望这个解释对您有所帮助!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|