我是C++新手,我写了一个简单的程序来实现友元函数的使用。代码如下:-
#include<iostream>
using namespace std;
class one
{
private:
int age;
public:
one()
{
age=1;
}
void setData(int num)
{
age=num;
}
friend int returnOne()
{
return age;
}
};
class two
{
private:
int roll;
public:
two()
{
roll=0;
}
void setData(int num)
{
roll=num;
}
friend int returnTwo()
{
return roll;
}
};
int main()
{
one a;
two b;
cout<<a.returnOne()<<endl<<b.returnTwo()<<endl;
}
我在 C++ 中遇到以下错误。
friend.cpp: In function ‘int returnOne()’:
friend.cpp:8:6: error: invalid use of non-static data member ‘one::age’
friend.cpp:20:9: error: from this location
friend.cpp: In function ‘int returnTwo()’:
friend.cpp:27:6: error: invalid use of non-static data member ‘two::roll’
friend.cpp:39:9: error: from this location
friend.cpp: In function ‘int main()’:
friend.cpp:47:10: error: ‘class one’ has no member named ‘returnOne’
friend.cpp:47:31: error: ‘class two’ has no member named ‘returnTwo’
编辑 谢谢。解决了问题。
但它现在让我想到另一个问题。friend 关键字现在是否损害了使用 private
的目的,因为现在任何类或函数都可以简单地使用friend函数来访问私有(private)数据成员。如果是,我们可以简单地将数据成员声明为 public
而不是 private
。使用 private
有什么特别之处?
最佳答案
看this链接
A friend function is a function that is not a member of a class but has access to the class's private and protected members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class's scope, and they are not called using the member-selection operators (. and –>) unless they are members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords.
关于c++ - 在 C++ 中使用友元函数时需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18482110/