只允许访问对象的成员,而不是对象本身

时间:2019-06-15 12:17:00

标签: c++ wrapper encapsulation forwarding

提供以下课程:

class Foo
{
public:

    //...

private:

    Bar mBar;
};

是否可以以一种可以访问其成员的方式公开mBar成员,但不能公开mBar对象本身?

原因是用户应该能够访问mBar的所有成员,但不能向Bar分配另一个mBar实例。 Bar的成员很多,因此为他们编写吸气剂/设定剂并转发功能将很麻烦。但是,如果将mBar设为公开,则可以执行aFoo.mBar = Bar(/*...*/);,这是唯一不应允许的事情。 不能删除Bar的赋值运算符。

2 个答案:

答案 0 :(得分:4)

如果您只想防止错误,而不是Machiavelli,则operator->可能会有所帮助(您可能希望使用包装器,而不是直接将其放在foo中):

class Foo
{
public:
    //...
    const Bar* operator ->() const { return &mBar; }
    Bar* operator ->() { return &mBar; }
private:
    Bar mBar;
};

如此

Foo foo;

foo->bar_member;
foo.foo_member;

// Machiavelli
*foo.operator->() = Bar();

答案 1 :(得分:1)

我可能会重新考虑您的设计,但这是使用中间get方法的一种间接方法:

struct Bar {
    int intAttr;
};

class Foo {
    Bar mBar;

public:

    template <class U>
    U& get(U Bar::* p) {
        return mBar.*p;
    }
};

通过这种方式,您可以使用以下方式访问mBar的任何公共成员:

Foo foo;
foo.get(&Bar::intAttr);      // get
foo.get(&Bar::intAttr) = 0;  // set
相关问题