C++ 命名空间和 类

C++ Namespaces and Classes

我想使用 class 中的常量而不调用 class,只需调用常量,如下所示:

头文件(.h)

class myClass{

   public: 
      const static char CHAR_S = '<';
}

源文件 (.cpp)

using namespace myClass;
char separator = CHAR_S; //I want to call the constant without using the class (myClass::CHAR_S)

我该怎么做?

最小的完整示例:

class MyClass {
    public:
    static const char CHAR_S = '<';
};

int main() {
    using namespace MyClass;
    char separator = CHAR_S;
    return 0;
}

导致以下编译器错误:

main.cpp: In function 'int main()':
main.cpp:7:21: error: 'MyClass' is not a namespace-name
     using namespace MyClass;
                     ^
main.cpp:7:28: error: expected namespace-name before ';' token
     using namespace MyClass;
                            ^
main.cpp:8:22: error: 'CHAR_S' was not declared in this scope
     char separator = CHAR_S;
                      ^
main.cpp:8:10: warning: unused variable 'separator' [-Wunused-variable]
     char separator = CHAR_S;
          ^

简单的技巧;参考重新定义它。这是一个例子。

Header.h

#ifndef __HEADER__
#define __HEADER__

class MyClass
{
public:
    const static char CHAR_S = '<';
    MyClass();
    ~MyClass();
};

#endif

Class.cpp

#include "MyClass.h"
const static char &CHAR_S = MyClass::CHAR_S;

MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}

myClass 不是命名空间,您不能那样使用它。我想你想要这样的东西:

namespace constants{
    const static char CHAR_S = '<';
};

using constants::CHAR_S;
int main(int argc, char ** argv)
{
    char a = CHAR_S;
    return 0;
}

A class 不是命名空间。如果不使用 class 名称进行限定,则无法引用 CHAR_S。

要执行您想要的操作,您只需将静态变量放在命名空间中即可:

namespace MyClass {
    static const char CHAR_S = '<';
} // namespace MyClass

int main() {
    using namespace MyClass;
    char separator = CHAR_S;
    return 0;
}

实例:http://coliru.stacked-crooked.com/a/74fcfee559cc1390

显然,调用您的命名空间 MyClass 会产生误导(因为它不是 class),因此选择一个更好的名称。

根据 C++ 标准(3.3.7 Class 范围)

2 The name of a class member shall only be used as follows:

— in the scope of its class (as described above) or a class derived (Clause 10) from its class,

— after the . operator applied to an expression of the type of its class (5.2.5) or a class derived from its class,

— after the -> operator applied to a pointer to an object of its class (5.2.5) or a class derived from its class,

— after the :: scope resolution operator (5.1) applied to the name of its class or a class derived from its class.

所以我认为唯一的方法是引入另一个引用 class 数据成员或具有其值的变量。例如

#include <iostream>

struct A
{
    const static char CHAR_S = '<';
};

const char A::CHAR_S;
const char &CHAR_S = A::CHAR_S;

int main()
{
    std::cout << CHAR_S << std::endl;
}