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

时间:2016-03-30 13:28:44

标签: c++ friend

看看我正在尝试实施的朋友功能

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

我知道它无法访问。但是我已经在课堂上定义了友元功能。那为什么它不可访问?谢谢

2 个答案:

答案 0 :(得分:2)

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

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

class City;
class Customer;

答案 1 :(得分:0)

经过测试的代码。只需要添加类City;

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