【问题标题】:How to access private member - array with friend function如何访问私有成员 - 具有好友功能的数组
【发布时间】:2016-02-02 08:11:07
【问题描述】:

我是 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;
}

【问题讨论】:

  • 很确定你的getCountry() 没有做你想做的事情(即它与string country[5] 无关,但总是创建并返回一个新分配的数组)。
  • 它甚至无法编译! country 必须是 string*,而不是 string
  • 避免使用new。这段代码充满了内存泄漏。请改用std::vector(这样您就不必担心长度问题)。虽然,想想看,你认为“string[5]”声明了一个(最多)五个字符长的字符串吗?它没有。它声明了五个空字符串,每个都可以是无限长度的。

标签: c++ arrays function friend


【解决方案1】:

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

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

请注意,名称也不匹配。

【讨论】:

  • 还要注意名称不匹配(一个是大写的“C”,另一个是小写的“c”)。
  • @MartinBonner 谢谢,已添加。
猜你喜欢
  • 2014-08-21
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 2021-11-15
相关资源
最近更新 更多