2012-10-03 78 views
3

我在下面的代碼中獲得跟隨STL compilation error無法將'this'指針從'const container <T>'轉換爲'container <T>'和'

#include <cstdio> 
#include <string> 

template <typename T> 
class container { 
public: 
    container(std::string in_key="") { 
    m_element_index = 0; 
    } 
    ~container() { 
    } 
    // Returns the numbers of elements in the container 
    int size() { 
    return m_element_index; 
    } 
    // Assignment operator 
    // Assigns a copy of container x as the new content for the container object. 
    container& operator= (const container& other) { 
    if (this != &other) { 
     for (int idx = 0; idx < other.size(); idx++) { 
     } 
    } 
    return *this; 
    } 
private: 
    int m_element_index; 
}; 

int main (int argc, char** argv) { 
    container<int> v1("my_container"); 
    container<int> v2("copy_cont"); 
    v2 = v1; 
} 

獲取錯誤以下行

for (int idx = 0; idx < other.size(); idx++) {

錯誤是

1>------ Build started: Project: test, Configuration: Debug Win32 ------ 
1> test.cpp 
1>e:\avinash\test\test\test.cpp(20): error C2662: 'container<T>::size' : cannot convert 'this' pointer from 'const container<T>' to 'container<T> &' 
1>   with 
1>   [ 
1>    T=int 
1>   ] 
1>   Conversion loses qualifiers 
1>   e:\avinash\test\test\test.cpp(18) : while compiling class template member function 'container<T> &container<T>::operator =(const container<T> &)' 
1>   with 
1>   [ 
1>    T=int 
1>   ] 
1>   e:\avinash\test\test\test.cpp(30) : see reference to class template instantiation 'container<T>' being compiled 
1>   with 
1>   [ 
1>    T=int 
1>   ] 
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 

回答

5

您需要更改此:

int size() { 
    return m_element_index; 
    } 

這樣:

int size() const { 
    return m_element_index; 
    } 

告訴編譯器,你想讓它允許size()要在const實例調用。

3

您需要聲明size()作爲const方法:

int size() const { 
    return m_element_index; 
} 

因爲在你的賦值運算符

container& operator= (const container& other) { .... } 

您呼叫other.size(),並otherreference-to-const,這意味着你只能叫常量方法。

4

這裏你傳遞一個const對象賦值操作符:

container& operator= (const container& other) { 
    <...> 
} 

然而,運營商裏面,您呼叫的othersize()功能:

for (int idx = 0; idx < other.size(); idx++) 

要使它可用於與const對象一起使用,函數本身必須聲明爲const

int size() const { 
    return m_element_index; 
} 
相關問題