无法实现我的简单友元函数 C++

not able to implement my simple friend function C++

看看我正在尝试实现的好友功能

#include <iostream>
#include <string>
using namespace std;
class Customer {
    friend void displayInfo(Customer, City);
private:
    int custNum;
    int zipCode;
};

class City {
    friend void displayInfo(Customer, City);
    string cityName;
    int zipCode;
};

void displayInfo(Customer cus, City city) {
    cout << cus.custNum; //compiler error - Inaccessible 
}

我知道它无法访问。但是我已经在 class 中定义了友元函数。那么为什么它不可访问呢?谢谢

当您将 displayInfo() 函数声明为 City 和 Customer 类 的友元时,作为参数(即在声明中)提供给 displayInfo 的 类 City 和 Customer 尚未定义.

如果您只是在代码的顶部添加两行,如图 here,它确实可以编译。

class City;
class Customer;

测试代码。只需添加 class 城市;

#include <iostream>
#include <string>
using namespace std;

class City;

class Customer {
    friend void displayInfo(Customer, City);
private:
    int custNum;
    int zipCode;
};

class City {
    friend void displayInfo(Customer, City);
    string cityName;
    int zipCode;
};

void displayInfo(Customer cus, City city) {
    cout << cus.custNum; //compiler error - Inaccessible 
}