我对下面这种常量版本和非常量版本的成员函数感到非常困惑:
value_type& top() { return this.item }
const value_type& top() const { return this.item }
这两个函数有什么区别?在什么情况下会使用它们?
我对下面这种常量版本和非常量版本的成员函数感到非常困惑:
value_type& top() { return this.item }
const value_type& top() const { return this.item }
这两个函数有什么区别?在什么情况下会使用它们?
value_type& top() { return this.item }
这用于提供对item
的可变访问。它被用于允许您修改容器中的元素。
例如:
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]
返回对元素的可变访问。
std::vector<int> v(5);
v[0] = 1; // Returns operator[] returns int&.
const value_type& top() const { return this.item }
这个用于提供对 item
的 const
访问。它比之前的版本更加严格,但是有一个优点 - 你可以在 const 对象上调用它。
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限定的。
如果调用非const限定的成员函数,则该成员函数将被调用,而对象不需要是const限定的。
例如:
MyStack s;
s.top(); // calls non-const member function
const MyStack t;
t.top(); // calls const member function
如果您有
class Foo
{
value_type& top() { return this.item }
const value_type& top() const { return this.item }
}
Foo foo;
const Foo cfoo;
top()
时返回的类型如下:value_type& bar = foo.top();
const value_type& cbar = cfoo.top();
item
),并确保它们也是常量 - 因此不可修改,从而保留了它们来自的实例的常量性。const
时,隐式传递给函数的this
指针参数会被声明为指向常量对象的指针类型。这使得该函数可以使用常量对象实例进行调用。value_type& top(); // this function cannot be called using a `const` object
const value_type& top() const; // this function can be called on a `const` object
value_type& top() { return this.item; }
确保调用对象的数据成员可以被修改或者返回值可以被修改。
value_type& top() const { return this.item; }
确保调用对象的数据成员不能被修改,但是返回值可以被修改。例如,如果我执行 value_type item_of_x = x.top();
,item_of_x
可以被修改,但是 x
不能被修改。否则,编译器会报错(例如在函数体内有 this.item = someValue;
的代码)。
const value_type& top() { return this.item; }
确保调用对象的数据成员可以被修改,但是返回值不能被修改。这与上面讨论的相反:如果我执行 const value_type item_of_x = x.top();
,item_of_x
不能被修改,但是 x
可以被修改。 注意 value_type item_of_x = x.top();
仍然允许修改 item_of_x
,因为 item_of_x
现在是非 const 的。
const value_type& top() const { return this.item; }
确保调用对象的数据成员和返回值都不能被修改。
mutable
是 C++ 的一个关键字,具有自己的含义,并不仅仅是const
的相反。你的问题更清晰地表述应该是:“const 成员函数和非 const 成员函数之间有什么区别?” - Josh Kelley