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ただし、演​​算子の内部では、 'ssize()関数を呼び出しています。

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()おり、これotherreference-to-constです。つまり、const メソッドのみを呼び出すことができます。

于 2012-10-03T12:42:18.967 に答える