gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:43:09 28 4
gpt4 key购买 nike

看看我正在尝试实现的友元函数

#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
}

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

最佳答案

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

如果您只是在代码的顶部添加两行,如图所示 here ,它会编译。

class City;
class Customer;

关于c++ - 无法实现我的简单友元函数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36310316/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com