2015-11-02 25 views
0

據我所知,C++只有基於參數或隱含對象參數的函數過載。但我發現有兩個運算符[]用於向量。它會在下面的代碼中選擇正確的功能:C++如何爲這個「vector [0] = 1;」重載分辨率「

std::vector<int> v; 
v[0] = 1; // This will select the non-const version. 
return &v[0]; // This will select the const version. 

任何人都可以解釋這是怎麼發生的?

 reference operator[] (size_type n); 
const_reference operator[] (size_type n) const; 

------編輯1 ------

我認爲它會選擇const版本,因爲下面的CC文件不能與鐺++編譯和g ++與下面的錯誤。不明白以下錯誤。任何人都可以解釋嗎?

error: cannot initialize return object of type 'char *' with an rvalue of type 'const value_type *' (aka 'const char *') return data_.size() == 0 ? NULL : (&data_[0]);

#include <assert.h> 

#include <deque> 
#include <vector> 
#include <map> 


class X 
{ 
public: 

    X() { 
    } 

    virtual ~X() { 
    } 

    char* data() const { 
     return data_.size() == 0 ? NULL : (&data_[0]); 
    } 

    size_t size() const { 
     return data_.size(); 
    } 


private: 
    std::vector<char> data_; 
}; 
+8

兩者都選擇非常量版本。 – Jarod42

+3

你爲什麼認爲'&v [0]'選擇了const版本? – emlai

+3

您的編輯使用'const'版本,因爲'data'函數標記爲'const'。 – TartanLlama

回答

7

其實在這兩種情況下的非const版本被調用。如果vectorconst,那麼將調用const版本的時間。

std::vector<int> const v = {1,2,3}; 
int x = v[0]; 

在上述情況下,嘗試調用非const版本將導致編譯器錯誤

v[0] = 5; // nope can't call non-const version, this is trying to mutate a const variable 

編輯
關於你提到的例子,根據你的函數

的簽名
char* data() const 

您已聲明方法dataconst,意思是它不應試圖改變任何成員變量。換句話說,const函數中的所有成員變量都被視爲const。在一個const方法的上下文中,變量被看作是

std::vector<char> const data_; 
1

由於v是一個非const vectorconst版本沒有被調用。

+1

除非通過引用或指向'const'的指針進行調用。 – emlai