We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
为什么把 string isbn() const {return bookNo;} 改为 string& isbn() const {return bookNo;} 编译会出错? 为什么这儿不能返回引用?
string isbn() const {return bookNo;}
string& isbn() const {return bookNo;}
struct Sales_data { string bookNo; unsigned units_sold = 0; double revenue = 0.0; string isbn() const {return bookNo;} Sales_data& combine(const Sales_data&); double avg_price() const; };
The text was updated successfully, but these errors were encountered:
为什么编译会出错?
返回引用, 就意味着外部调用的时候, 可能对 bookNo 进行修改. 但你又对该成员函数进行了 const 修饰. 这又意味着, 外部调用者无权对该对象进行任何修改. 显然, 这两者是矛盾的. 于是编译器就困惑了...
const
为什么这儿不能返回引用?
当然可以返回引用, 但你要保证行为遵循逻辑, 如:
std::string& isbn() { return bookNo; } // 返回引用 const std::string& isbn() { return bookNo; } // 返回 const 引用 const std::string& isbn() const { return bookNo; } // 针对 const 对象返回 const 引用
上述三种改法, 都是可以的.
Sorry, something went wrong.
懂了。 非常感谢!
No branches or pull requests
为什么把
string isbn() const {return bookNo;}
改为string& isbn() const {return bookNo;}
编译会出错? 为什么这儿不能返回引用?The text was updated successfully, but these errors were encountered: