在 C++ 中隐藏父类但不隐藏祖父母

问题描述 投票:0回答:1

在班级可见性方面是否可以跳过一代?

以下适用于 gcc 编译器,但不适用于 clang 或 intel。他们失败了

error: cannot cast 'C' to its protected base class 'A'

struct A {};
struct B: public A {int stuff() {} };
struct C: protected B { using B::A; }; // want to hide stuff from `B`, but keep the identity as an `A`

void call(A &) {}

int main()
{
    C c;
    call(c);
}

GCC 在这种情况下是否过度通融还是正确的?

本例中的

A
B
代表两个无法更改的类。为了使解决方案可用,必须在
C
类中完成。

c++ inheritance using-declaration
1个回答
0
投票

C++ 标准草案第 9.9 节第 16 段提供了以下示例:

class A {
private:
    void f(char);
public:
    void f(int);
protected:
    void g();
};

class B : public A {
  using A::f;       // error: A​::​f(char) is inaccessible
public:
  using A::g;       // B​::​g is a public synonym for A​::​g
};

在这种情况下,很明显,人们应该能够编程

B().g();
并让该语句在 B 的临时实例中调用
B::g

在问题中,

A::B
命名了一个类型,所以我应该认为
using A::B;
的效果应该是允许在
C::A instance_of_A;
形式的声明类之外使用,GCC和Clang都接受。

但是,作为副作用,GCC 在

C::B::A
的实例中公开受保护的基类
C
似乎是 GCC 编译器方面的不一致性。

© www.soinside.com 2019 - 2024. All rights reserved.