これらのコードスニペットはかなり短いですが、constキーワードで何が欠けているのか分かりません。私は、関数定義の後のconstを入れたときに私の最初のスニペットでは、それだけで何かを返すことは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; ^
そして第二に、私は単純に返す置きます。これを返す代わりに*これ。私は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;
}
* const-correctness *と呼ばれています。 constから暗黙的に非constに行くことはできません。 – NathanOliver