【发布时间】: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