【发布时间】:2013-08-28 08:20:59
【问题描述】:
我刚刚开始学习 C++ 中的友元函数。这是我用于概念探索的程序。
#include<iostream>
using namespace std;
class one
{
private:
int age;
public:
one()
{
age=1;
}
void setData(int num)
{
age=num;
}
friend int returnOne(one a);
};
int returnOne(one a)
{
return a.age;
}
class two
{
private:
int roll;
public:
two()
{
roll=0;
}
void setData(int num)
{
roll=num;
}
friend int returnTwo(two b);
};
int returnTwo(two b)
{
return b.roll;
}
int main()
{
one a;
two b;
a.setData(10);
b.setData(12);
cout<<returnOne(a)<<endl<<returnTwo(b)<<endl;
}
现在我担心one 和two 类的安全性受到威胁,因为现在任何人都可以使用这些全局定义的朋友函数来访问one 类和two 类的私有成员。
如何为这些好友功能提供保护或限制其使用?
【问题讨论】:
-
您不应将私有/受保护/公共视为安全概念。将某些内容设为私有或受保护并不能保护其免受恶意用户的攻击,这只是一个设计问题,以便更容易编写更好的代码。
标签: c++ friend friend-function