gpt4 book ai didi

c++ - 使用声明和访问修饰符的嵌套类

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:45:22 29 4
gpt4 key购买 nike

在编译一些代码时,我遇到了一个编译器错误,这个错误对我来说很奇怪,并且与继承、嵌套类、使用声明和访问修饰符有关。

基本上,派生类型的目的是公开基类型的嵌套 protected 类。

以下简短示例演示了该问题:

class Base
{
protected:

struct Nested
{
enum value_enum
{
val = 0,
val2,
val3
};
};

};

class Derived : public Base
{
public:

using Base::Nested;
};


int main(int argc, char** argv)
{
//Base::Nested aa; // error, as (I) expected
//Base::Nested::value_enum ab; // error, as (I) expected

Derived::Nested ba; // works, as (I) expected
Derived::Nested::value_enum bb; // MSVC error, as (I) did not expect


return 0;
}

参见 live .

MSVC11 (v11.00.61030) 在此代码上阻塞并出现以下错误:

error C2248: 'Base::Nested' : cannot access protected struct declared in class 'Base'

GCC 和 Clang 都能正确编译它,因此无法从标准中引用相关部分,我认为这是一个 MSVC 错误。

MSVC 有办法解决这个问题吗?

最佳答案

对于 MSVC,以下解决方法有效:

class Derived : public Base
{
public:

using Base::Nested;
typedef Base::Nested::value_enum value_enum; // add this
};

int main(int argc, char** argv)
{
//Base::Nested aa; // error, as (I) expected
//Base::Nested::value_enum ab; // error, as (I) expected

Derived::Nested ba; // works, as (I) expected
Derived::value_enum bb = Derived::value_enum::val; // now works in MSVC


return 0;
}

关于c++ - 使用声明和访问修饰符的嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32436466/

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