所以我有这个小片段,它认为“abc”不是字符串而是 const char [4],所以我无法将它分配给我的对象。我搜索过但没有找到任何可行的解决方案。提前致谢。
Tekst t = "abc";
Tekst Tekst::operator=(std::string& _text){
return Tekst(_text);
}
编辑:由于这是我的面向对象编程类(class)中几乎所有练习的主要内容,无论出于何种原因,我们都无法更改 int main()
中的任何内容,因此更改 Tekst t = "abc";
是不行的。
编辑 2:Tekst(std::string _text) :text(_text) {};
最佳答案
编译器认为 "abc"
是const char [4]
。它是 const char [4]
而您认为它应该是 std::string
,这是不正确的。 std::string
可以从 const char *
隐式构造,但它们远不相同。
你的问题实际上是你试图绑定(bind)一个临时的到一个非常量引用,这在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]
}
但是,这对您的情况没有帮助,因为主要问题是将临时引用绑定(bind)到非常量引用。
关于C++ 2440 错误 - 编译器认为字符串是 const char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58825457/