[英]What's the difference between a const member function and a non-const member function?
我对const版本和非const版本成员函数感到困惑,如下所示:
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
注意,在对对象的引用或通过对象的指针调用成员函数时,将应用相同的规则:如果指针或引用是const对象,则将调用const成员函数;否则,将调用const成员函数。 否则将调用非常量成员函数。
如果你有
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();
换句话说-如果您的类具有常量实例,则将函数的const版本选择为要调用的重载。
这样做的原因(在这种情况下)是为了使您可以从类的const实例中给出对成员(在这种情况下,如item
)的引用,并确保它们也为const-因此不可修改,因此保留了const。他们来自的实例的程度。
当成员函数声明为const
,发生的是传递给函数的隐式this
指针参数被键入为指向const对象的指针。 这允许使用const对象实例调用该函数。
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() { return this.item; }
确保可以修改调用对象的数据成员,也可以修改返回值。
value_type& top() const { 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& 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 value_type& top() const { return this.item; }
const value_type& top() const { return this.item; }
确保既不能修改调用对象的数据成员,也不能修改返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.