如何在 C++ 中定义字符串常量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7571278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:09:23  来源:igfitidea点击:

How do I define string constants in C++?

c++classdefinition

提问by Thom

Possible Duplicate:
C++ static constant string (class member)
static const C++ class member initialized gives a duplicate symbol error when linking

可能的重复:
C++ 静态常量字符串(类成员)
静态常量 C++ 类成员初始化在链接时给出重复符号错误

My experience with C++ pre-dated the addition of the string class, so I'm starting over in some ways.

我在 C++ 方面的经验早于字符串类的添加,所以我在某些方面重新开始。

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:

我正在为我的班级定义头文件,并希望为 url 创建一个静态常量。我正在尝试这样做:

#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?

我怎样才能做到这一点?

采纳答案by David Nehme

Move the

移动

const std::string MainController::SOME_URL = "www.google.com";

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.

到一个cpp文件。如果您将它放在标题中,那么包含它的每个 .cpp 都会有一个副本,并且您将在链接期间收到重复符号错误。

回答by JRL

You need to put the line

你需要把线

const std::string MainController::SOME_URL = "www.google.com";

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::stringis not an integral type (like int).

在 cpp 文件中,而不是标题中,因为一个定义规则。并且您不能在类中直接初始化它的事实是因为std::string它不是整数类型(如 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.

或者,根据您的用例,您可能会考虑不创建静态成员,而是使用匿名命名空间。有关利弊,请参阅此帖子

回答by Nawaz

Define the class in the header file:

在头文件中定义类:

//file.h
class MainController{
private:
    static const std::string SOME_URL;
}

And then, in source file:

然后,在源文件中:

//file.cpp
 #include "file.h"

const std::string MainController::SOME_URL = "www.google.com";

回答by Mark B

You should put the const std::string MainController::SOME_URL = "www.google.com";definition into a single source file, not in the header.

您应该将const std::string MainController::SOME_URL = "www.google.com";定义放在一个源文件中,而不是放在头文件中。