为什么我不能为命名空间中的变量赋值? [英] Why can't I assign a value to a variable in a namespace?

查看:90
本文介绍了为什么我不能为命名空间中的变量赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下,当我编译它时,我收到这个错误:

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

two.cpp:5: 错误:'= 之前的预期构造函数、析构函数或类型转换'令牌

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.

我正在学习 Beginning ANSI C++,在书中找不到任何相关信息.

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

推荐答案

命名空间的目的是避免名称冲突.所以用命名空间包围你的变量和类声明.但是命名空间本身并不为运行代码提供脚手架.你的 a=4 是怎么回事;陈述 ?那应该在哪里执行?您需要将其放在函数或方法中,而不是放在命名空间中.

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.

这篇关于为什么我不能为命名空间中的变量赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆