允许“朋友”类只能访问一些私人成员 [英] Allowing a "friend" class to access only some private members

查看:64
本文介绍了允许“朋友”类只能访问一些私人成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个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:

这是面向密钥的吗

这篇关于允许“朋友”类只能访问一些私人成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆