在c++中使用友元函数时需要帮助

need help in using friend functions in c++

本文关键字:帮助 函数 友元 c++      更新时间:2023-10-16

我是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函数来访问私有数据成员。如果是,我们可以简单地将数据成员声明为public而不是private。使用private有什么特别之处?

查看此链接

友元函数是一个函数,它不是类的成员,但可以访问类的私有成员和受保护成员。朋友函数不被视为类成员;它们是正常的外部被赋予特殊访问权限的函数。朋友不在类的作用域,并且不会使用成员选择来调用它们运算符(.和–>),除非它们是另一个类的成员。A.friend函数由授予访问权限的类声明。这个友元声明可以放在类声明的任何位置。它不受访问控制关键字的影响。