简体   繁体   中英

Why can't I assign a value to a variable in a namespace?

My code is like below, when I compile it , I receive this error :

two.cpp:5: error: expected constructor, destructor, or type conversion before '= ' token

#include <iostream>
using namespace std;
namespace a1{
    int a=3;
    a=4;
}

int main(){
    cout << a1::a<<endl;
}

I encountered this problem when I defined a namespace in two files, in the second file, I can't assign a value to a variable which defined in the first file.

I am learning Beginning ANSI C++ , and can't find any information about this in the book.

You can have declarations (which include that you can have definitions) at namespace scope, eg

int a = 3;

But you can not have non-declaration statements at namespace scope.

For example, an assignment such as

a = 4;

is not a declaration: it purely asks for an effect.

However, you can put that in the body of a function, eg in main .

Cheers & hth.,

The purpose of namespaces is to avoid conflicting names. So surround your variable and class declarations with namespaces. But namespaces by themselves don't provide the scaffolding for running code. What is going on with your a=4; statement ? Where is that supposed to execute ? You need to put it in a function or method, not in a namespace.

Does your second file knows about the definition of int a; ? Namespaces don't magically work like in some other languages, you still have to include a header file containing the definition of your int a at the other file, or at list define it as external.

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