在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关键字现在不是损害了使用private
的目的吗?因为现在任何类或函数都可以简单地使用friend函数来访问私有数据成员。如果是,我们可以简单地将数据成员声明为public
而不是private
。使用private
有什么特别之处?
查看此链接
友元函数是一个函数,它不是类的成员,但可以访问类的私有成员和受保护成员。朋友函数不被视为类成员;它们是正常的外部被赋予特殊访问权限的函数。朋友不在类的作用域,并且不会使用成员选择来调用它们运算符(.和–>),除非它们是另一个类的成员。A.friend函数由授予访问权限的类声明。这个友元声明可以放在类声明的任何位置。它不受访问控制关键字的影响。
相关文章:
- 需要帮助将结构数组传递给函数
- C++调用具有 *this 属性的单个帮助程序函数
- 用于检查值是否为其任何参数的帮助程序函数
- 无法将 2D 数组传递到 c++ 中的帮助程序函数中
- 在确定函数的时间复杂度时需要帮助
- C2783: 无法推断帮助程序函数的模板参数
- 友元函数需要一个帮助程序函数
- 在何处放置与类方法相关的帮助程序函数C++
- 需要帮助将字符串插入函数
- 从函数打印 CLI 帮助消息后,我应该如何干净地退出 C++ 程序?
- 类参数化与类和帮助程序函数混淆
- 需要有关在 C++ 中的函数 display() 上查找未定义引用的帮助
- 如何使用类中的函数从 main 打印变量,帮助理解 OOP c++
- 函数无法正常工作,调试器没有帮助
- 为什么这段代码不直接使用 C++ 幂函数?有人可以帮助我使用此代码中的电源函数吗?
- 函数和指针帮助:程序生成,但崩溃,没有任何特定错误
- 需要帮助理解 2D 数组并将其传递到函数中
- 在哪里/如何声明和实现必须由成员方法使用的帮助函数
- c++ 11指针惟一帮助函数
- 有人可以帮助函数重载吗?