我有一个类需要在构造期间连接两个 const char*
字符串,甚至稍后在初始化列表中使用结果(连接的字符串)。
const char* SUFFIX = "suffix";
class widget {
public:
widget(const char* prefix) : key(???), cls(key) { };
private:
const char* key;
const important_class cls;
}
widget("prefix_"); // key should be prefix_suffix
有一个全局(在 widget
的 cpp 中)const char*
后缀,我想将其附加到用户提供的前缀。
怎么做?
顺便说一句。我听说过 string
。如果我可以使用 string
我就不会在这里问 const char*
最佳答案
使用 std::string
使您的问题变得微不足道:
const std::string SUFFIX = "suffix";
class widget {
public:
widget(std::string const & prefix)
: key(prefix + SUFFIX), cls(key)
{ } // ^^^^^^^^^^^^^^concatenation!
private:
const std::string key;
const important_class cls;
}
widget("prefix_");
如果您需要 const char*
,您仍然可以通过调用返回 const char*
的 key.c_str()
来获取它。所以在你的情况下,它会给你 c-string "prefix_suffix"
。
另请注意声明的顺序很重要,您已正确完成:cls
必须在 key
之后声明,因为它的构造取决于在键
上。
关于c++ - 在类构造函数中安全地连接 C 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15294334/