3

STL compilation error在以下代码中得到关注。

#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 ==========
4

3 回答 3

5

你需要改变这个:

  int size() {
    return m_element_index;
  }

对此:

  int size() const {
    return m_element_index;
  }

告诉编译器您希望它允许size()const实例上调用。

于 2012-10-03T12:42:12.420 回答
4

在这里,您将一个 const 对象传递给赋值运算符:

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

但是,在运算符内部,您正在调用other'size()函数:

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

为了使其可用于const对象,函数本身必须声明为const

int size() const {
    return m_element_index;
}
于 2012-10-03T12:44:37.167 回答
3

您需要声明size()const方法:

int size() const {
    return m_element_index;
}

因为在你的赋值运算符中

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

您正在调用other.size(),并且other是 a reference-to-const,这意味着您只能在其上调用 const 方法。

于 2012-10-03T12:42:18.967 回答