如何访问私有成员 - 具有友元函数的数组

How to access private member - array with friend function

本文关键字:友元 函数 数组 成员 访问 何访问      更新时间:2023-10-16

我是C++新手,我写代码来看看朋友函数是如何工作的。这里有两个类,我要求朋友函数中的用户提供参数,如果它们与成员变量的值相等,则显示这些参数。而且我无法访问其中一个私人成员 - 带有国家/地区名称的数组。在函数int elcountry(element &e, supply s)中,我试图显示特定类型和特定国家的元素数量。错误是无法访问 elCountry 函数中的成员supply::country, (s.country[i])。我不知道如何使用getCountry()函数来访问私有数组。

class element {
        friend class supply;
    private:
        string name;
        double value;
        int serial;
    public:
        element();
        int elCountry(element &e, supply &s);
         double* nominals(element &e, supply &s);
        string getName() {
            return name;
        }
        int getSerial() {
            return serial;
        }
    };
    class supply {
    private:
        int serial;
        string country[5];
        int n;
    public:
        supply();
        string* getCountry() {
            string country = new string[5];
                return country;
        }
        friend int elCountry(element &e, supply &s);
        friend double* nominals(element &e, supply &s);
    };
    int elcountry(element &e, supply s){
        string names, Country;
        int n;
        cout << "enter country = "; cin >> Country;
        cout << "enter name of the element = "; cin >> names;
        cout << "enter number of elements = "; cin >> n;
        for (int i = 0; i < 5; i++) {
            if (Country == s.country[i] && names  == e.getName() && n ==  e.getSerial()) {
                cout << "the country is " << count << endl;
                cout << "the name is" << names << endl;
                cout << "the number is " << n << endl;
            }
        }
           return n;
}

两个函数的签名不匹配,它们无关紧要,根本不friend函数。

friend int elCountry(element &e, supply &s);
             ~                          ~
int elcountry(element &e, supply s){
      ~

请注意,名称也不匹配。