【问题标题】:cannot be used to initialize an entity of type const std::string *不能用于初始化 const std::string * 类型的实体
【发布时间】:2014-06-25 18:33:36
【问题描述】:

我在头文件中定义了以下常量:

class Example {

public:
    const static string* days_strs[];
    const static char* days_chars[];
};

并在 example.cpp 文件中实现它们:

    const static string* Example::days_strs[] = {"monday", "tuesday", ...};
    const static char* Example::days_chars[] = {"m", "t", ...};

我为什么要得到 ​​p>

days_str[]

“错误:值“const char*”不能用于初始化“const std::string *”类型的实体

【问题讨论】:

  • 尝试删除 *: const static string Example::days_strs[] = {"monday", "tuesday", ...} 和类似的 days_chars。对于days_chars,使用单引号,例如'm', 't', etc.
  • 只需使用const std::string。根本不需要指针。您可能还想要第二个 const char,因为它们是单个字符。
  • 嗯,string* Example::days_strs[]string 指针的静态数组。你想要的是一个字符串数组,而不是字符串指针。与days_chars 类似,您需要一个字符数组,而不是字符指针数组。
  • 谢谢大家的回答!对不起愚蠢的问题。我是 C++ 新手,特别是这个指针...
  • @Xerath 没有愚蠢的问题,至少我是这么认为的。祝您在 C++ 之旅中好运。

标签: c++ arrays string


【解决方案1】:

我认为你的意思是以下

class Example {

public:
    const static string days_strs[];
    const static char* days_chars[];

};

//...

   const string Example::days_strs[] = {"monday", "tuesday", ...};
   const char* Example::days_chars[] = {"m", "t", ...};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 2019-08-25
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多