c++ - 在类构造函数中安全地连接 C 字符串

标签 c++ cstring

我有一个类需要在构造期间连接两个 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/

相关文章:

c++ - 有没有办法从内存文件处理程序加载图标?

c++ - 如何在 Windows 8 64 位操作系统中注册 .DLL 文件?

c++ - C++ Battery Collector 教程的编译错误

c++ - 如何用字符串文字优雅地初始化 vector<char *>?

c++ - 如何在 C++ 中创建一组无序的整数对?

c++ - 如何在小框中显示 Unicode 值?

c - 没有逗号的数组初始化

c++ - 将 int 转换为 base 2 cstring/string

c - 为什么我没有收到段错误?

c - 如何将指针传递给字符串数组 (char *p[]) ?