【发布时间】:2017-09-08 02:34:15
【问题描述】:
这些 sn-ps 的代码非常短,但我无法理解 const 关键字缺少什么。在我的第一个 sn-p 中,当我将 const 放在函数定义之后时,它表示仅返回某些内容会使 const 关键字不合格:
string & getText() const {
return txt;
}
jdoodle.cpp:在成员函数'std::__cxx11::string& Document::getText() const'中: jdoodle.cpp:29:16: 错误:绑定'const string {aka const std::__cxx11::basic_string}' 到类型'std::__cxx11::string& {aka std::__cxx11::basic_string&}' 的引用丢弃限定词 返回.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:在成员函数'File& File::operator=(const File&)'中: jdoodle.cpp:117:16:错误:将“const File”绑定到“File&”类型的引用丢弃限定符 返回一个; ^
最后,第三个(当我像现在这样放入实际的修改器时,它会引发违规错误——与我只放入成员变量时不同):
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;
}
【问题讨论】:
-
它被称为const-correctness。您不能隐式地从 const 转到非 const。