开发者

How do I define string constants in C++? [duplicate]

This question already has answers here: Closed 11 years ago.

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?


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.


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::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:

//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";


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜