编译一些代码,我遇到编译器错误,这对我来说很奇怪,并且与继承,嵌套类,使用声明和访问修饰符有关。
基本上,目的是使派生类型公开基类型的嵌套受保护类。
以下简短示例来说明问题:
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)对此代码进行了阻塞,并出现以下错误:
错误C2248:' Base :: Nested' :无法访问在类' Base'
中声明的受保护结构
GCC和Clang都正确地编译了这个,所以如果不能引用标准中的相关部分,我认为这是一个MSVC错误。
使用MSVC可以解决这个问题吗?
答案 0 :(得分:1)
对于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;
}