C ++ 2440错误-编译器认为字符串是const char?

所以我有一个小片段,它认为“ 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) {};

gandong5050 回答:C ++ 2440错误-编译器认为字符串是const char?

编译器不认为 "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引用。

,

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

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

,

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

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

Tekst(const char *_text) :text(_text) {};
本文链接:https://www.f2er.com/3114773.html

大家都在问