使用声明不能引用类成员

问题描述 投票:0回答:3

基本上,在名称空间Foo中定义了一个类np

//Foo.h
namespace np {

    class Foo {
        public:
          static void static_member();
         ...
        }
...
}

我想在其他来源中引用静态成员,例如src.cc

//src.cc
#include "Foo.h"

using np::Foo::static_member;
...
static_member()
...

启动编译器后,它抱怨:

 error: using declaration cannot refer to class member

但是,当我将行更改为np::Foo::static_member()时,它起作用了。那么,什么是省略无限范围前缀的正确方法呢?

c++ namespaces static-methods
3个回答
1
投票

那么,什么是省略无限范围前缀的正确方法?

没有办法。在类范围之外,using声明可以引用类中的嵌套types,但不能引用数据成员,请参见here

您能得到的最短的一个是

using namespace np;
Foo::static_member();

或带有指向成员的指针,该指针更短,但也更加混乱:

auto static_member = &np::Foo::static_member;
static_member();

0
投票

您不必添加using np::Foo::static_member;


0
投票

我不确定您的用例是什么,但是我会采用以下两种方法之一(也许是三种?):

© www.soinside.com 2019 - 2024. All rights reserved.