从子类初始化受保护的静态成员
Initialize the protected static member from the subclass
我想知道是否可以从 subclass.
初始化受保护的静态成员
例如,
// head file
class Test
{
protected:
static int i;
};
class Test2 : public Test{};
//cpp file
#include "headfile.h"
int Test2::i = 1;
如您所见,当我初始化这个静态成员 (i) 时,我使用了 subclass 名称 (Test2)。
令我惊讶的是,我用 visual studio 2013 测试了这段代码,它没有出错。但是,如果我在 Linux 下使用 Netbeans(gcc11) 尝试它,我得到一个提示错误:
unable to resolve the identifier i
然后我编译了一下,报错信息是:
error: ISO C++ does not permit ‘Test::i’ to be defined as ‘Test2::i’ [-fpermissive]
现在,如果我在 class 测试中将 static int i
的 protected 更改为 public,错误将消失。
我很困惑...这是我第一次发现 gcc 和 vs. 有两个不同的结果
该定义违反了 C++14 [class.static.data] §9.4.2/2。强调我的:
In the definition at namespace scope, the name of the static data
member shall be qualified by its class name using the ::
operator.
较新版本的 GCC(在 Coliru 上)的行为与限定符无关。您可以使用 -fpermissive
消除 GCC 上的错误,但请注意,您仍然只定义一个对象,属于基础 class.
我想知道是否可以从 subclass.
初始化受保护的静态成员
例如,
// head file
class Test
{
protected:
static int i;
};
class Test2 : public Test{};
//cpp file
#include "headfile.h"
int Test2::i = 1;
如您所见,当我初始化这个静态成员 (i) 时,我使用了 subclass 名称 (Test2)。
令我惊讶的是,我用 visual studio 2013 测试了这段代码,它没有出错。但是,如果我在 Linux 下使用 Netbeans(gcc11) 尝试它,我得到一个提示错误:
unable to resolve the identifier i
然后我编译了一下,报错信息是:
error: ISO C++ does not permit ‘Test::i’ to be defined as ‘Test2::i’ [-fpermissive]
现在,如果我在 class 测试中将 static int i
的 protected 更改为 public,错误将消失。
我很困惑...这是我第一次发现 gcc 和 vs. 有两个不同的结果
该定义违反了 C++14 [class.static.data] §9.4.2/2。强调我的:
In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the
::
operator.
较新版本的 GCC(在 Coliru 上)的行为与限定符无关。您可以使用 -fpermissive
消除 GCC 上的错误,但请注意,您仍然只定义一个对象,属于基础 class.