小编ach*_*nge的帖子

C++ 命名空间和 const 变量

我在 win10 中使用 Visual studio 2019 将这些文件编译为单个程序

我的项目只有两个源文件:

/**** a.cpp ****/

namespace pers{
    const int LEN = 5;
}
Run Code Online (Sandbox Code Playgroud)

/**** b.cpp ****/

namespace pers {
    const int LEN = 5;
}

int main() {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

可以编译成功,但是不知道为什么?我定义了LEN两次!!

所以,我删除了const

/**** a.cpp ****/

namespace pers{
    int LEN = 5;
}
Run Code Online (Sandbox Code Playgroud)

/**** b.cpp ****/

namespace pers {
    int LEN = 5;
}

int main() {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在不行了!所以,我的问题是发生了什么事?const不同源文件中的变量可以定义两次或多次(意味着不会出现多重定义错误)。

同时,如果这样做,编译器将抛出“多重定义错误”:

namespace pers {
    const int LEN …
Run Code Online (Sandbox Code Playgroud)

c++

4
推荐指数
1
解决办法
479
查看次数

标签 统计

c++ ×1