繁体   English   中英

在使用C ++中的朋友功能时需要帮助

[英]need help in using friend functions in c++

我是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函数来访问私有数据成员,所以friend关键字现在是否已经损害了使用private的目的。如果是的话,我们可以简单地声明它们数据成员是public而不是private 。使用private什么特别之处?

这个链接

朋友函数是不是类成员但可以访问该类的私有成员和受保护成员的函数。 朋友功能不视为班级成员; 它们是普通的外部功能,具有特殊的访问权限。 朋友不在该类的范围内,除非它们是另一个类的成员,否则不使用成员选择运算符(。和–>)来调用它们。 授予访问权限的类声明了一个朋友功能。 朋友声明可以放在类声明中的任何位置。 它不受访问控制关键字的影响。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM