简体   繁体   English

基类中的私有静态成员

[英]Private static member in base class

#include <iostream>
#include <string>

class Base
{
    static std::string s;
};

template<typename T>
class Derived
    : Base
{
public:
    Derived()
    {
        std::cout << s << std::endl;
    }
};

std::string Base::s = "some_text";    

int main()
{
    Derived<int> obj;
}

This programs compiles and runs normally. 该程序编译并正常运行。 static variable s is private in base class that is inherited privately. 静态变量s在私有继承的基类中是私有的。 How is Derived class accessing it? Derived类如何访问它?

If Derived class is not template, compiler complains about accessing private variable. 如果Derived类不是模板,则编译器会抱怨访问私有变量。

[aminasya@amy-aminasya-lnx c++]$ g++ --version
g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

This is definitely a GCC bug, equivalent to GCC Bug 58740 : 这绝对是一个GCC错误,相当于GCC Bug 58740

class A {
    static int p;
};
int A::p = 0;
template<int=0>
struct B : A {
    B() {(void)p;}
};
int main() {
    B<>();
}

The bug is still open, and this code still compiles on 5.1. 该错误仍处于打开状态,此代码仍在5.1上编译。 GCC has issues with template member access, this is just another such example. GCC存在模板成员访问问题,这只是另一个这样的例子。

I think this is a compiler bug, as this compiles with gcc but not clang, for me. 我认为这是一个编译器错误,因为这对我编译gcc而不是clang。

Edit: as an additional data point, this bug does not seem to have been fixed, as I can reproduce in gcc 4.9.2 and 5.1. 编辑:作为一个额外的数据点,这个错误似乎没有修复,因为我可以在gcc 4.9.2和5.1中重现。

It's a bug in g++ 4.8.4. 这是g ++ 4.8.4中的一个错误。 The code compiles, only if Derived is a template and the member is static. 仅当Derived是模板且成员是静态时,代码才会编译。

Tests: 测试:

  • template static compiles 模板静态编译
  • no template static fails 没有模板静态失败
  • template not static fails 模板不是静态失败
  • no template not static fails 没有模板不静态失败

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM