简体   繁体   中英

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'

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 .

The first declaration

char &ns::x = y;

assumes that the name x is already declared in the namespace 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.

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 .

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; 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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