c++ - 在 C++ 中使用类的命名空间定义类的成员

标签 c++ class using

我有几个名字很长的类和它们的成员函数。在 C++ 中,有一个技巧允许您使用一个命名空间并声明函数:

namespace_name::foo();

然后这样定义它:

namespace namespace_name{
    foo() {}
}

为了代码的清晰度,我想知道是否有类似的方法来替换函数的定义:

LongClassName::LongFunctionName() {}

如果我使用了不当的词汇,我很抱歉,但我不知道如何描述这个问题。

最佳答案

In C++ there is a trick which allows you to use one namespace and turn

这个“技巧”允许您调用函数而无需指定带命名空间的完整函数名称。对于既不适用于命名空间也不适用于类的函数定义。对于命名空间级别的函数,您要么必须将该函数定义放在命名空间内,要么明确提及:

 namespace foo {
     void bar(); // foo::bar() declared
 }

 // you can define it as this
 namespace foo {
     void bar() {}
}

// or this
void foo::bar() {}

// this does not work
using namespace foo;
void bar() {} // ::bar() is defined here not foo::bar()

对于类方法定义 - 必须始终使用类名(如果有的话,也可能使用命名空间),除非您在类本身内部定义它们(并隐式声明它们 inline):

class VeryLongName {
public:
    void method1() {}
    void method2() {}
};

关于c++ - 在 C++ 中使用类的命名空间定义类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51546950/

相关文章:

c# - 使用 Using 和 Yield Return 从文件中读取文本行

datatable - 我应该 Dispose() DataSet 和 DataTable 吗?

c++ - 如何打印其中包含整数的字符串 C++

python - 从另一个文件导入类及其功能

c++ - 无法在汇编中链接 C++ 函数

python - 你怎么知道两个对象什么时候可以通信?

Swift,传递的segue信息不会显示

c++ - 为什么 C++11 中没有模板化的 typedef?

c++ - 拥有一个与非线程局部变量同名的线程局部变量是否可以?

C++ : Help needed to debug generic linked list