[英]Templated member functions cannot call non-templated member function from same class, C++
[英]Why *this returned from a const member function cannot be used to call other functions in C++?
我得到以下代码:
class Book
{
public:
void print();
const Book &Book::get();
};
void Book::print()
{
cout << "print()" << endl;
}
const Book &Book::get()
{
cout << "get()" << endl;
return *this;
}
然后我做了:
Book b;
b.get().print(); // This did not work. Why is that?
它可以调用其他函数,但在这种情况下不能。
您正在从get()
返回const Book &
。 然后,这将调用print()
,这是一个非常量函数。 要解决此问题,请使print()
const:
void print() const;
void Book::print() const
{
cout << "print()" << endl;
}
此const确保您对象的状态不会更改,这与您从get()
返回的const对象一致。 请注意,它可以更改mutable
成员,因为这是它们的全部目的。
编辑:顺便说一下,您要查找的术语是method chaining
。
Book :: print()不是const成员函数,因此不能用Book :: get()返回的const Book引用调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.