如何仅将基类公开为 const 引用

Dan*_*uer 5 c++ inheritance const-correctness

我希望我的类仅Foo将其基类公开Bar为对Bar. 这意味着 的成员Bar可以读取,但不能设置。这是我尝试过的:

struct Bar
{
    int member;
};

class Foo : protected Bar
{
public:
    operator const Bar&() { return *this; }
};
Run Code Online (Sandbox Code Playgroud)

但在使用时,会出现以下问题:

int getBarMember( const Bar& bar )
{
    return bar.member;
}

int main()
{
    Foo myFoo;

    const Bar& refBar = myFoo; // C2243
    // const Bar& refBar = (const Bar&) myFoo; // always need to cast explicitly

    int read = refBar.member;

    int readByFunction = getBarMember( myFoo ); // C2243
    // int readByFunction = getBarMember( (const Bar&) myFoo ); // always need to cast explicitly
}
Run Code Online (Sandbox Code Playgroud)

我希望能够调用采用 const 引用的函数,而Bar无需显式强制转换。

编译器错误是:

C2243:从“Foo *”到“const Bar&”的“转换类型”转换存在,但无法访问

Yks*_*nen 5

我认为这是不可能的,gcc 和 clang 对操作员发出以下警告:

<source>:12:5: warning: converting 'Foo' to a reference to a base class 'Bar' will never use a type conversion operator [-Wclass-conversion]
  12 |     operator const Bar&() { return *this; }
     |     ^~~~~~~~
Run Code Online (Sandbox Code Playgroud)

如果在您的真实代码中可行,您可以使用组合优于继承的原则并执行以下操作(在线查看):

struct Bar
{
    int member;
};

class Foo 
{
public:
    operator const Bar&() { return parent; }
protected:
    Bar parent;
};
Run Code Online (Sandbox Code Playgroud)

Bar它可能需要对您在 内部访问的方式进行一些更改Foo,但它无需对外部世界进行强制转换即可工作。