C++ 私有扩展后转 public 一个变量

C++ turn public a variable after private extending

疑惑如题:

加上class如下:

class A
{
public:
    int a;
    int b;
    int c;

    function1();
    function2();
}

和一个class B扩展A,如何从A转public所有变量?

class B : private A
{
public:
    int a; //How to turn this public from A
    int b; //How to turn this public from A
    int c; //How to turn this public from A
}

使用其他继承选项

  class B: public A

读这个Difference between private, public, and protected inheritance

不要在 B 中重新声明它们。

示例:

class A {
public:
    int a;
    int b;
    int c;

    void function1() {  }
    void function2() {  }
};

// Use private inheritance
class B : private A {
public:
    using A::a;
    using A::b;
    using A::c;

private:
    void function3()
    {
        // 'a' exists here, as it is defined public in base class A
    }
};

int main()
{
    B b;
    b.a = 1;

    b.function1(); // error: ‘A’ is not an accessible base of ‘B’

    return 0;
}

将私有基础 class 的 public 数据和成员公开为派生 class 中的 public 数据是一个坏主意。但是,如果必须,您可以使用:

class B : private A
{
   public:
      using A::a;
      using A::b;
      using A::c;
};

我觉得你可以

class B : private A
{
public:
    int A::a; 
    int A::b; 
    int A::c; 
}

不过,我没试过;