简体   繁体   中英

Why *this returned from a const member function cannot be used to call other functions in C++?

I got the following code:

class Book
{
public:
    void print();
    const Book &Book::get();
};
void Book::print()
{
    cout << "print()" << endl;
}
const Book &Book::get()
{
    cout << "get()" << endl;
    return *this;
}

Then I did:

Book b;
b.get().print(); // This did not work. Why is that?

It can call other functions, but not in this case.

You're returning a const Book & from get() . This is then calling print() , which is a non-const function. To fix this, make print() const:

void print() const;

void Book::print() const
{
    cout << "print()" << endl;
}

This const ensures your object's state will not be changed, which complies with the const object you return from get() . Note that it can change mutable members though, as that's their whole purpose.

Edit: By the way, the term you're looking for is method chaining .

Book :: print()不是const成员函数,因此不能用Book :: get()返回的const Book引用调用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM