如何在 C++ 中定义字符串常量?
我使用 C++ 的经验早于添加字符串类,因此我在某些方面重新开始。
我正在为我的类定义头文件,并希望为 url 创建一个静态常量。我正在尝试执行以下操作:
#include <string>
class MainController{
private:
static const std::string SOME_URL;
}
const std::string MainController::SOME_URL = "www.google.com";
但这在链接期间给了我一个重复的定义。
我怎样才能做到这一点?
Possible Duplicate:
C++ static constant string (class member)
static const C++ class member initialized gives a duplicate symbol error when linking
My experience with C++ pre-dated the addition of the string class, so I'm starting over in some ways.
I'm defining my header file for my class and want to create a static constant for a url. I'm attempting this by doing as follows:
#include <string>
class MainController{
private:
static const std::string SOME_URL;
}
const std::string MainController::SOME_URL = "www.google.com";
But this give me a duplicate definition during link.
How can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将其
移至 cpp 文件。如果您将其放在标头中,则包含它的每个 .cpp 都会有一个副本,并且您将在链接期间收到重复符号错误。
Move the
to a cpp file. If you have it in a header, then every .cpp that includes it will have a copy and you will get the duplicate symbol error during the link.
由于
单一定义规则。事实上,您不能直接在类中初始化它,因为
std::string
不是整型(如 int)。或者,根据您的用例,您可能会考虑不创建静态成员,而是使用匿名命名空间。 请参阅这篇文章了解优点/缺点。
You need to put the line
in the cpp file, not the header, because of the one-definition rule. And the fact that you cannot directly initialize it in the class is because
std::string
is not an integral type (like int).Alternatively, depending on your use case, you might consider not making a static member but using an anonymous namespace instead. See this post for pro/cons.
在头文件中定义类:
然后在源文件中:
Define the class in the header file:
And then, in source file:
您应该将 const std::string MainController::SOME_URL = "www.google.com"; 定义放入单个源文件中,而不是放在标头中。
You should put the
const std::string MainController::SOME_URL = "www.google.com";
definition into a single source file, not in the header.