基类中的私有静态成员
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;
}
该程序编译并正常运行。静态变量s
在私有继承的基类中是私有的。派生类如何访问它?
如果派生类不是模板,编译器会报错访问私有变量。
[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.
这绝对是一个GCC bug,相当于GCC bug 58740:
class A {
static int p;
};
int A::p = 0;
template<int=0>
struct B : A {
B() {(void)p;}
};
int main() {
B<>();
}
这个bug仍然是打开的,并且这个代码仍然可以在5.1上编译。GCC在模板成员访问方面有问题,这只是另一个这样的例子。
我认为这是一个编译器错误,因为它可以用gcc编译,而不是clang。
编辑:作为一个额外的数据点,这个错误似乎没有被修复,因为我可以在gcc 4.9.2和5.1中重现。
这是g++ 4.8.4中的一个bug。只有当Derived
是模板且成员为静态时,代码才会编译。
测试:
- 模板静态编译
- 没有模板静态失败
- 模板非静态失败
- 模板非静态失败
相关文章:
- 使用静态成员声明类时遇到问题
- 使用派生类中的静态成员而不是基类
- 从相同类型的静态成员进行类内初始化
- 具有静态成员的类的前向声明
- 枚举不是非静态数据成员或类的基类
- boost::bind 无法绑定到纯虚拟基类中定义的非静态函数模板成员类型
- 在没有显式作用域的情况下无法访问模板基类的静态成员
- C++ - 在派生类中静态初始化受基类保护的成员变量
- 为了在测试中调用destuructor(用于测试),静态铸造基类有多么可怕
- 访问指定为私有的基类的公共静态成员
- 如果基类是公开继承的,那么基类的公共静态函数是否会成为派生类的成员函数
- 指向成员的 C++ 指针(指向成员基类的指针)
- 成员初始值设定项"超类"不命名非静态数据成员或基类
- 具有静态成员的类包含C++中的静态成员
- 模板基类的静态成员不会导出到共享库
- C++-Do派生类继承基类的静态成员
- 在包含其自身类型的静态成员的类中使用 __declspec(dllimport)
- 为什么静态成员的类内初始化会违反 ODR
- 命名空间中的函数重载(与具有静态成员的类相比)是个坏主意吗
- 如何在c++中将模板成员函数的实参转发给成员基类指针