Skip to content
New issue

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

p231 中 string isbn() const {return bookNo;} #125

Closed
TolicWang opened this issue Jun 1, 2017 · 2 comments
Closed

p231 中 string isbn() const {return bookNo;} #125

TolicWang opened this issue Jun 1, 2017 · 2 comments
Labels

Comments

@TolicWang
Copy link

TolicWang commented Jun 1, 2017

为什么把 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;
};
@pezy
Copy link
Owner

pezy commented Jun 1, 2017

为什么编译会出错?

返回引用, 就意味着外部调用的时候, 可能对 bookNo 进行修改. 但你又对该成员函数进行了 const 修饰. 这又意味着, 外部调用者无权对该对象进行任何修改. 显然, 这两者是矛盾的. 于是编译器就困惑了...

为什么这儿不能返回引用?

当然可以返回引用, 但你要保证行为遵循逻辑, 如:

std::string& isbn() { return bookNo; } // 返回引用
const std::string& isbn() { return bookNo; } // 返回 const 引用
const std::string& isbn() const { return bookNo; } // 针对 const 对象返回 const 引用

上述三种改法, 都是可以的.

@pezy pezy added the question label Jun 1, 2017
@TolicWang
Copy link
Author

懂了。 非常感谢!

@pezy pezy closed this as completed Jun 1, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants