c – 无法将’this’指针从’const container’转换为’container&’

c – 无法将’this’指针从’const container’转换为’container&’,第1张

概述我在以下代码中遇到了STL编译错误. #include <cstdio>#include <string>template <typename T>class container {public: container(std::string in_key="") { m_element_index = 0; } ~container() { } // Retu 我在以下代码中遇到了STL编译错误.

#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.cpp1>e:\avinash\test\test\test.cpp(20): error C2662: 'container<T>::size' : cannot convert 'this' pointer from 'const container<T>' to 'container<T> &'1>          with1>          [1>              T=int1>          ]1>          Conversion loses qualifIErs1>          e:\avinash\test\test\test.cpp(18) : while compiling class template member function 'container<T> &container<T>::operator =(const container<T> &)'1>          with1>          [1>              T=int1>          ]1>          e:\avinash\test\test\test.cpp(30) : see reference to class template instantiation 'container<T>' being compiled1>          with1>          [1>              T=int1>          ]========== Build: 0 succeeded,1 Failed,0 up-to-date,0 skipped ==========
解决方法 你需要改变这个:

int size() {    return m_element_index;  }

对此:

int size() const {    return m_element_index;  }

告诉编译器你希望它允许在const实例上调用size().

总结

以上是内存溢出为你收集整理的c – 无法将’this’指针从’const container’转换为’container&’全部内容,希望文章能够帮你解决c – 无法将’this’指针从’const container’转换为’container&’所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1219770.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存