gpt4 book ai didi

c++ - 如果我返回一个const定义的对象,为什么const关键字不合格?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:08:18 26 4
gpt4 key购买 nike

这些代码片段非常短,但我不明白我在 const 关键字中遗漏了什么。在我的第一个代码片段中,当我将 const 放在函数定义之后时,它表示仅返回某些内容会取消 const 关键字的资格:

string & getText() const {
return txt;
}

jdoodle.cpp: In member function 'std::__cxx11::string& Document::getText() const': jdoodle.cpp:29:16: error: binding 'const string {aka const std::__cxx11::basic_string}' to reference of type 'std::__cxx11::string& {aka std::__cxx11::basic_string&}' discards qualifiers return txt; ^

第二个,当我简单地把 return a;而不是返回 *this;我最终违反了 const 关键字。

File & operator = (const File & a) {
this->drive = a.drive;
this->folder = a.folder;
this->fileName = a.fileName;
this->txt = a.txt;
this->fullPath = a.fullPath;
return a;
}

jdoodle.cpp: In member function 'File& File::operator=(const File&)': jdoodle.cpp:117:16: error: binding 'const File' to reference of type 'File&' discards qualifiers return a; ^

最后,第三个(当我像现在这样放入实际的修改器时,它会抛出违规错误——这与我只放入成员变量时不同):

File & File::operator = (File & a) {
this->getDrive() = a.getDrive();
this->getFolder() = a.getFolder();
this->getFileName() = a.getFileName();
this->getText() = a.getText();
this->fileName = a.fileName;
return a;
}

最佳答案

作为赋值运算符时,you probably want to return *this .

话虽如此,您仍然遇到有关 getter 函数丢弃限定符的错误。

即使我建议您直接在赋值运算符中使用成员,也可以按照以下方法修复代码。

您的 getter 函数可能如下所示:

string& getText() {
return txt;
}

您需要为 const 对象提供一个额外的重载:

const string& getText() const {
return txt;
}

这里的区别是 this 和每个成员都是 const 在一个 const 限定的函数中。由于您要返回对该字符串的引用,它更常量,因此您需要返回一个常量引用。

通过提供 const 和非 const 版本,您仍然可以改变 getter 返回的对象,并且有一个额外的重载将使非可变 getter 与非可变对象一起工作。

关于c++ - 如果我返回一个const定义的对象,为什么const关键字不合格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46107775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com