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

时间:2013-08-28 07:48:11

标签: c++ class oop friend friend-function

我是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’

修改 谢谢。它解决了这个问题。

但现在它引出了另一个问题。好友关键字现在已经破坏了使用private的目的,因为现在任何类或函数都可以简单地使用友元函数来访问私有数据成员。如果是,我们可以简单地将数据成员声明为public而不是private。使用private时有什么特别之处?

1 个答案:

答案 0 :(得分:4)

查看this链接

  

友元函数是一个不是类成员的函数   可以访问该类的私有和受保护成员。朋友   职能不被视为集体成员;他们是正常的外部   具有特殊访问权限的函数。朋友不在   类的范围,并且不使用成员选择调用它们   运算符(。和 - &gt;)除非它们是另一个类的成员。一个   friend函数由授予访问权限的类声明。该   朋友声明可以放在类声明的任何地方。它   不受访问控制关键字的影响。