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