gpt4 book ai didi

c++ - 基类中的私有(private)静态成员

转载 作者:IT老高 更新时间:2023-10-28 22:12:21 25 4
gpt4 key购买 nike

#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 在私有(private)继承的基类中是私有(private)的。派生类如何访问它?

如果派生类不是模板,编译器会提示访问私有(private)变量。

[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 错误,相当于 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 在模板成员访问方面存在问题,这只是另一个这样的例子。

关于c++ - 基类中的私有(private)静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31298566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com