【问题标题】:Hide private members from a friend class隐藏朋友类的私人成员
【发布时间】:2022-11-13 16:31:24
【问题描述】:

我想要一个具有公共和私有方法的类“Foo”,以及一个可以访问 Foo 的一些私有方法但不是所有私有成员的朋友类“Bar”。

class Foo
{
private:

    friend class Bar;

    // hidden from Bar
    int x = 0;

    // visible to Bar
    void setX(int value)
    {
        x = value;
    }

public:

    int getX()
    {
        return x;
    }

};

class Bar
{
public:

    void modifyFoo(Foo& foo)
    {
        foo.setX(5);
    
        // should produce an error
        //foo.x = 5;
    }

};

【问题讨论】:

  • 附带说明:对友元类或函数的需求通常表明类层次结构和接口设计不佳。恕我直言,这应该完全保留用于单元测试某些特殊情况。

标签: c++ private friend-class


【解决方案1】:

您可以在基类中隐藏私有成员,然后让 Foo 成为该基类的孩子和朋友(非常感人)。

#include <iostream>

// forward declare Foo so we can make it a friend of FooPrivate
class Foo;

// allows us to hide instance members from friends of Foo,
// but still allows Foo itself to access them.
class FooPrivate
{
private:

    friend class Foo;
    
    // only allow Foo to derive from this class
    FooPrivate() {};
    
    // hidden from friends of Foo
    int x = 0;

};

// this class hides some of its private members from friend classes
class Foo : public FooPrivate
{
public:

    int getX()
    {
        return x;
    }

private:

    // give Bar access to private method
    friend class Bar;
    
    void setX(int value)
    {
        x = value;
    }

};

class Bar
{
public:

    void modifyFoo(Foo& foo)
    {
        foo.setX(5);
        
        // error: 'x' is a private member of 'FooPrivate'
        //foo.x = 4;
    }

};

int main()
{
    Foo foo;
    
    // prints "0"
    std::cout << foo.getX() << std::endl;
    
    Bar bar;
    bar.modifyFoo(foo);
    
    // prints "5"
    std::cout << foo.getX() << std::endl;
}

任何你想对 Bar 隐藏的东西都可以放入 FooPrivate(必须是私有成员),其他所有东西都可以直接放入 Foo。 Foo 将能够访问 FooPrivate 中的所有内容,就像它自己的成员一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-16
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    相关资源
    最近更新 更多