简体   繁体   English

命名空间内 C++ 中的变量声明

[英]Variable declaration in C++ within namespaces

In a library I am working with some variables are declared like that:在我正在使用的库中,一些变量的声明如下:

char &ns::x = y;

However, if I do it that way I get the following error: error: no member named 'x' in namespace 'ns'但是,如果我这样做,我会收到以下错误: error: no member named 'x' in namespace 'ns'

If I rewrite it, it works:如果我重写它,它会起作用:

namespace ns {
    char &x = y;
}

What exactly is the difference?究竟有什么区别? And why is it working within the library?为什么它在图书馆内工作?

If you're right and the code from the library is exactly as written, then this implies that elsewhere in this library, you'll find the following declaration:如果您是对的并且库中的代码与编写的完全相同,那么这意味着在该库的其他地方,您将找到以下声明:

namespace ns {
    extern char& x;
}

In other words, x must have already been declared (and not defined!) inside ns .换句话说, x必须已经在ns声明(并且未定义!)。

The first declaration第一次声明

char &ns::x = y;

assumes that the name x is already declared in the namespace ns .假定名称x已在命名空间ns中声明。 However this assumption is wrong (in the provided code snippet there is no previous declaration of the variable. Possibly the code snippet is not complete.).然而这个假设是错误的(在提供的代码片段中没有先前的变量声明。可能代码片段不完整。)。

The code snippet can works provided that the variable x is already declared (without its definition) in the namespace ns.如果变量 x 已经在命名空间 ns 中声明(没有定义),则代码片段可以工作。

For example例如

#include <iostream>

namespace ns
{
    extern char &x;
}

char y;
char & ns::x = y;

int main() {
    return 0;
}

In this code snippet在此代码段中

namespace ns {
    char &x = y;
}

there is defined a reference that is initialized by the object y .定义了一个由 object y初始化的引用。

The Variable declaration using namespace:使用命名空间的变量声明:

#include <iostream> 
using namespace std; 

// Variable created inside namespace 
namespace first 
{ 
  int val = 500; 
} 
// Global variable 
int val = 100; 
int main() 
{ 
// Local variable 
   int val = 200; 
// These variables can be accessed from 
// outside the namespace using the scope 
// operator :: 
   cout << first::val << '\n';  
   return 0; 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM