簡體   English   中英

const成員函數和非const成員函數有什么區別?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM