如果我返回const定义的对象,为什么const关键字被取消资格?

时间:2017-09-08 02:34:15

标签: c++ const

这些代码片段很短,但我无法理解 const 关键字所缺少的内容。在我的第一个片段中,当我在函数定义之后放置const时,它表示只返回一些东西会使const关键字失去资格:

string & getText() const {
    return txt;
}
  

jdoodle.cpp:在成员函数' std :: __ cxx11 :: string& Document :: getText()const':   jdoodle.cpp:29:16:error:binding' const string {aka const std :: __ cxx11 :: basic_string}'引用类型' std :: __ cxx11 :: string& {aka std :: __ cxx11 :: basic_string&}'丢弃限定符            return txt;                   ^

第二,当我简单地回归一个;而不是返回*这个;我最终违反了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:在会员功能'文件& File :: operator =(const File&)':   jdoodle.cpp:117:16:错误:绑定' const文件'参考类型' File&'丢弃限定符            返回;                   ^

最后,第三个(当我像现在一样放入实际的mutators时,它抛出了违规错误 - 不像我刚刚放入成员变量时):

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;
}

1 个答案:

答案 0 :(得分:1)

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

话虽如此,你仍然得到关于你的getter函数丢弃限定符的错误。

即使我建议您直接在作业运算符中使用成员,也可以通过以下方式修改代码。

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

string& getText() {
    return txt;
}

您需要为const对象提供附加重载:

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

这里的区别在于this,并且const限定函数中的每个成员都是const。由于您希望返回对该字符串的引用(更多为const),因此需要返回const引用。

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