问题描述
假设我有三个C ++类FooA,FooB和FooC。
Suppose I have three C++ classes FooA, FooB and FooC.
FooA有一个名为 Hello
的成员函数。 ,我想在FooB类中调用此函数,但是我不希望FooC类能够调用它。我能弄清楚的最好方法是将FooB声明为FooA的朋友类。但是,只要我这样做,所有 FooA的私有成员和受保护成员将被暴露出来,这对我来说是完全不可接受的。
FooA has an member function named Hello
, I want to call this function in class FooB, but I don't want class FooC be able to call it. The best way I can figure out to realize this is to declare FooB as a friend class of FooA. But as long as I do this, all FooA's private and protected members will be exposed which is quite unacceptable to me.
所以,我想知道C ++(03或11)中是否有比 friend
类更好的机制可以解决这个难题。
So, I wanna know if there is any mechanism in C++(03 or 11) better than friend
class which can solve this dilemma.
如果可以使用以下语法,我认为它会很好:
And I assume it will be nice if the following syntax is possible:
class FooA
{
private friend class FooB:
void Hello();
void Hello2();
private:
void Hello3();
int m_iData;
};
class FooB
{
void fun()
{
FooA objA;
objA.Hello() // right
objA.Hello2() // right
objA.Hello3() // compile error
ojbA.m_iData = 0; // compile error
}
};
class FooC
{
void fun()
{
FooA objA;
objA.Hello() // compile error
objA.Hello2() // compile error
objA.Hello3() // compile error
ojbA.m_iData = 0; // compile error
}
};
推荐答案
没有什么可以让一个类成为特定朋友的函数,但您可以将 FooB
用作带有私有构造函数的键类的朋友,然后使 FooA :: Hello
将该类作为忽略的参数。 FooC
将无法提供参数,因此无法调用 Hello
:
There's nothing to make a class a friend of one specific function, but you can make FooB
a friend of a "key" class with private constructor, and then have FooA::Hello
take that class as an ignored parameter. FooC
will be unable to provide the parameter and hence can't call Hello
:
这篇关于允许“朋友”类只能访问一些私人成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!