gpt4 book ai didi

c++ - 使用声明不能引用类成员

转载 作者:行者123 更新时间:2023-11-27 22:33:01 25 4
gpt4 key购买 nike

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

//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() 时它起作用了。那么,省略无休止的范围前缀的正确方法是什么?

最佳答案

So, what are proper ways to omit the interminable scope prefixes?

没有办法。在类作用域之外,using 声明可以引用类中的嵌套类型,但不能引用数据成员,参见here .

你能得到的最短的是

using namespace np;
Foo::static_member();

或者使用指向成员的指针,它更短但也更容易混淆:

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

关于c++ - 使用声明不能引用类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58553964/

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