我剛開始學習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(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
的私有成員。 如何爲這些朋友功能提供保護或限制其使用?
您不應該將private/protected/public視爲安全概念。製作私密或受保護的內容並不能保護它免受惡意用戶的侵害,這只是一個設計問題,可以使編寫更好的代碼變得更容易。 – Wilbert