C++ 友元函数错误分析:Person 类中的 show 函数未声明为 student 类友元
C++ 友元函数错误分析:Person 类中的 show 函数未声明为 student 类友元
代码问题分析
这段代码中,Person 类中的 show 函数需要访问 student 类私有成员 score,但没有被声明为 student 类友元函数,因此无法访问。
错误代码:
#include<iostream>
using namespace std;
class student;
class Person
{
public:
Person(string newname)
{
this->name = newname;
}
void show(student &a);
private:
string name;
};
void Person::show(student &a)
{
cout << a.score << endl;
}
class student
{
friend void Person::show(student &a);
public:
student(int newscore)
{
this->score = newscore;
}
private:
int score;
};
int main()
{
Person p('张三');
student P2(12);
p.show(P2);
return 0;
}
错误原因:
在 Person 类中,show 函数没有被声明为 student 类友元函数,导致无法访问 student 类的私有成员 score。
解决方法
为了解决这个问题,需要在 Person 类中将 show 函数声明为 student 类友元函数。
修改后的代码:
#include<iostream>
using namespace std;
class student;
class Person
{
public:
Person(string newname)
{
this->name = newname;
}
friend void show(student &a); // 将show函数声明为student类的友元函数
private:
string name;
};
void show(student &a) // 定义show函数
{
cout << a.score << endl;
}
class student
{
friend void show(student &a); // 将show函数声明为student类的友元函数
public:
student(int newscore)
{
this->score = newscore;
}
private:
int score;
};
int main()
{
Person p('张三');
student P2(12);
show(P2); // 调用show函数
return 0;
}
解释
- 友元函数: 友元函数是允许其他类访问其私有成员的特殊函数。在上面的代码中,show 函数被声明为 student 类友元函数,因此它可以访问 student 类的私有成员 score。
- friend 关键字: 在类定义中使用 friend 关键字来声明友元函数。
总结
通过将 show 函数声明为 student 类友元函数,我们可以解决代码中的错误,并正确访问 student 类的私有成员。友元函数机制提供了灵活的访问权限控制,方便不同类之间的相互操作。
原文地址: https://www.cveoy.top/t/topic/wAk 著作权归作者所有。请勿转载和采集!