C ++中私有静态成员变量的继承

时间:2019-07-18 09:01:49

标签: c++ templates inheritance static-members

我遇到了模板问题,并访问了派生类中基类的静态私有成员。

似乎我可以从模板化派生类中非法访问基类私有成员变量。

#include <iostream>

class Foo {
public:

  Foo() {};
  ~Foo() {};

private:

  static int some_variable;

};

int Foo::some_variable;

template<typename T>
class Bar : Foo {
public:

  Bar(T bla) {
    some_variable = bla;
  };
  ~Bar() {};

  void test() {
    std::cout << some_variable << std::endl;
  }
};

int main()
{
  Foo A;

  Bar<int> B(2);
  B.test();
}

我希望此代码不会编译,因为派生类尝试访问父类中的私有变量。 但是,它使用gcc(g++ -std=c++11 -O3 test.cpp -Wall -Wextra)进行编译时没有错误或警告,但使用clang(clang -x c++ test.cpp)进行编译时,会抛出有关变量是私有成员的错误

删除“ some_variable”非静态会导致g ++错误,而使“ Bar”成为非模板化类也会导致g ++错误。 我在这里想念什么?

我的g ++版本是(Ubuntu 5.4.0-6ubuntu1〜16.04.11)5.4.0 20160609

0 个答案:

没有答案