为什么“静态”全局const char是否需要,但布尔不是? [英] Why is "static" needed for a global const char but not for a bool?

查看:90
本文介绍了为什么“静态”全局const char是否需要,但布尔不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

共享标题。

我可以这样做:

const bool kActivatePlayground = false;

当包含在多个文件中时效果很好。

Works fine when included among multiple files.

我不能为此:

const char * kActivePlayground = kiddiePool;

结果错误:重复的符号。

Results in error: duplicate symbols.

但这可行:

static const char * kActivePlayground = kiddiePool;

为什么静态 const char * 所必需的,但不是 const bool 所必需的?另外,我认为静态是不必要的,因为 const 总是 static 隐式?

Why is the static needed for the const char * but not for the const bool ? Additionally, I thought static is not necessary since const is always static implicity?

推荐答案

在C ++中,默认情况下 const 变量具有静态链接,而非 const 变量具有外部链接。

In C++, const variables by default have static linkage, while non-const variables have external linkage.

出现多个定义错误的原因是

The reason for the multiple definitions error is that

const char * kActivePlayground = "kiddiePool";

创建具有外部链接的变量。

creates a variable with external linkage.

嘿,等等,我不是只是说 const 变量默认为静态链接吗?是的,我做到了。但是 kActivePlayground 不是 const 。它是指向 const char 的非 const 指针。

Hey wait, didn't I just say that const variables default to static linkage? Yes I did. But kActivePlayground is not const. It is a non-const pointer to const char.

这将按您的预期工作:

const char * const kActivePlayground = "kiddiePool";

这篇关于为什么“静态”全局const char是否需要,但布尔不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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