基 class 中的私有静态成员
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
在基 class 中是私有的,它是私有继承的。 Derived class 如何访问它?
如果 Derived class 不是模板,编译器会抱怨访问私有变量。
[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 而不是 clang 编译的。
编辑:作为一个额外的数据点,这个错误似乎没有被修复,因为我可以在 gcc 4.9.2 和 5.1 中重现。
这是 g++ 4.8.4 中的错误。仅当 Derived
是模板且成员是静态成员时,代码才能编译。
测试:
- 模板静态编译
- 没有模板静态失败
- 非静态模板失败
- 没有非静态模板失败
这绝对是一个 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<>();
}
错误仍然存在,此代码仍可在 5.1 上编译。 GCC 在模板成员访问方面存在问题,这只是另一个例子。
#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
在基 class 中是私有的,它是私有继承的。 Derived class 如何访问它?
如果 Derived class 不是模板,编译器会抱怨访问私有变量。
[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 而不是 clang 编译的。
编辑:作为一个额外的数据点,这个错误似乎没有被修复,因为我可以在 gcc 4.9.2 和 5.1 中重现。
这是 g++ 4.8.4 中的错误。仅当 Derived
是模板且成员是静态成员时,代码才能编译。
测试:
- 模板静态编译
- 没有模板静态失败
- 非静态模板失败
- 没有非静态模板失败
这绝对是一个 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<>();
}
错误仍然存在,此代码仍可在 5.1 上编译。 GCC 在模板成员访问方面存在问题,这只是另一个例子。