一个const成员函数和一个非const成员函数有什么区别? [英] What's the difference between a const member function and a non-const member function?
问题描述
我非常困惑的const版本和非const版本成员函数如下:
I am very confused about the const version and non-const version member function like below:
value_type& top() { return this.item }
const value_type& top() const { return this.item }
这两个函数有什么区别?
What is the difference between these two functions? In what situation would they be used?
推荐答案
简而言之,它们用于在程序中添加const correctness。
In short, they're used to add 'const correctness' to your program.
value_type& top() { return this.item }
这用于提供对 item
。它被使用,因此您可以修改容器中的元素。
This is used to provide mutable access to item
. It is used so you can modify the element in the container.
例如:
c.top().set_property(5); // OK - sets a property of 'item'
cout << c.top().get_property(); // OK - gets a property of 'item'
这种模式的一个常见示例是返回可变访问到 vector :: operator [int index]
的元素。
One common example for this pattern is returning mutable access to an element with vector::operator[int index]
.
std::vector<int> v(5);
v[0] = 1; // Returns operator[] returns int&.
另一方面:
const value_type& top() const { return this.item }
const 访问项
。它比以前的版本限制更多 - 但它有一个优势 - 你可以调用它的const对象。
This is used to provide const
access to item
. It's more restrictive than the previous version - but it has one advantage - you can call it on a const object.
void Foo(const Container &c) {
c.top(); // Since 'c' is const, you cannot modify it... so the const top is called.
c.top().set_property(5); // compile error can't modify const 'item'.
c.top().get_property(); // OK, const access on 'item'.
}
按照向量示例:
const std::vector<int> v(5, 2);
v[0] = 5; // compile error, can't mutate a const vector.
std::cout << v[1]; // OK, const access to the vector.
这篇关于一个const成员函数和一个非const成员函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!