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

标签 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’

编辑 谢谢。解决了问题。

但它现在让我想到另一个问题。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/

相关文章:

c++ - 使用 cuBlas 将矩阵与其转置相乘

c++ - 如何在C/C++中计算最多1000位的数字的位数

python - 使用 python3 为 msvc 构建 boost python - 链接器错误

c++ - 重载 cmath 函数 C++ 时出现函数重载错误

java - 如何将输出语句转换为字符串类型?

java - 将 null 传递给首选 String 而不是 Object 的方法

javascript - 如何编写 JavaScript 模板类?

c++ - new Object() 和 Object() 有什么区别

c# - 如何使用 OOP 进行设计

oop - 如何向必须实现所需初始值设定项的子类添加所需属性?