【问题标题】:C++ 2440 error - compiler thinks string is const char?C++ 2440 错误 - 编译器认为字符串是 const char?
【发布时间】:2020-03-08 13:30:39
【问题描述】:

所以我有这个小sn-p,它认为“abc”不是字符串而是const char [4],所以我不能将它分配给我的对象。我已经搜索但没有找到任何可行的解决方案。提前致谢。

Tekst t = "abc";
Tekst Tekst::operator=(std::string& _text){
    return Tekst(_text);
}

编辑:由于这是我的面向对象编程课程中几乎所有练习的主要内容,无论出于何种原因,我们都无法更改int main() 中的任何内容,因此更改Tekst t = "abc"; 是不行的。

编辑 2:Tekst(std::string _text) :text(_text) {};

【问题讨论】:

  • 您的 operator= 看起来不正确。 Here's如何正确操作。
  • "它认为 "abc" 不是字符串,而是 const char [4]" 它并不“认为”它是。 "abc" 实际上是 const char [4] 类型。为什么你认为应该是std::string
  • 另外,您能edit your question 并发布Tekst 的构造代码吗?
  • 提供operator=(const char*)怎么样?
  • 另外,相关Why not non-const reference to temporary objects?。 TLDR:如果您使用const 引用参数:Tekst Tekst::operator=(std::string const& _text) 它会编译。

标签: c++ string class char constants


【解决方案1】:

Tekst t = "abc"; 只是Tekst t("abc"); 的语法糖,这意味着它根本不考虑您的operator=,而是使用类的构造函数。

为了编译Tekst t = "abc";,您需要一个接受const char*const std::string& 作为输入的构造函数。但是,您展示的构造函数采用 std::string 值而不是 const 引用,因此它不能用于字符串文字。所以你需要为此添加一个新的构造函数:

Tekst(const char *_text) :text(_text) {};

【讨论】:

    【解决方案2】:

    感谢@Ted Lyngmo,“这应该会有所帮助:godbolt.org/z/j_RTHu”,结果我所要做的就是添加一个单独的构造函数来接收 const char*

    Tekst(const char* cstr) : Tekst(std::string(cstr)) {}

    【讨论】:

    • 这不是你的问题的答案。 @Yksisarvinen 的回答是。
    • 我尝试按照他告诉我的做,但没有奏效,所以我想我没有搞清楚。
    • 额外的构造函数是另一个转换构造函数,就像Tekst(const std::string&);一样。使用Tekst t = "abc"; 语法时,它只能尝试一次隐式转换(从const char[4]Tekst),但由于您没有这样的转换构造函数,因此您必须添加它。
    【解决方案3】:

    编译器不认为 "abc"const char [4]。是const char [4],你认为应该是std::string,这是不正确的。 std::string 可以从 const char * 隐式构造,但它们相差甚远。

    你的问题实际上是你试图将一个临时的绑定到一个非常量引用,这在 C++ 中是不可能的。您应该将运算符的定义更改为

    Tekst Tekst::operator=(const std::string& _text){
    //                     ^ const here
        return Tekst(_text);
    }
    

    这将使您的运算符在技术上有效(例如,它可以编译并且没有未定义的行为)。然而,它做了一些非常不直观的事情。考虑以下几点:

    Tekst t;
    t = "abc";
    

    在本例中,t 内部不会有任何"abc"。新返回的对象被丢弃,t 不变。

    很可能,您的运算符应该如下所示:

    Tekst& Tekst::operator=(const std::string& _text){
        this->text = _text; //or however you want to change your object
        return *this;
    }
    

    请参阅the basic rules and idioms for operator overloading,了解有关每个运算符的期望和不期望的更多信息。


    在半相关的注释中,您可以从 C++14 及更高版本的文字中获得 std::string

    #include <string>
    
    using namespace std::string_literals;
    
    int main() {
        auto myString = "abc"s; 
        //myString is of type std::string, not const char [4]
    }
    

    但是,这对您的情况没有帮助,因为主要问题是将临时引用绑定到非常量引用。

    【讨论】:

    • 即使使用 const std::string&amp; 也会失败,并出现相同的错误 C2440。
    • @Baltr 那是在你的构造函数上,而不是operator=
    • @Baltr 你必须为此展示你的构造函数,但作为 80% 的猜测,你还需要给它一个参数 const std::string&amp;
    • 将构造函数更改为Tekst(const std::string&amp; _text) :text(_text) {}; 仍然得到同样的错误
    猜你喜欢
    • 2018-07-12
    • 2017-03-29
    • 2016-05-29
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多