c – 无法将’this’指针从’const container’转换为’containe
发布时间:2020-12-16 10:23:03 所属栏目:百科 来源:网络整理
导读:我在以下代码中遇到了STL编译错误. #include cstdio#include stringtemplate typename Tclass container {public: container(std::string in_key="") { m_element_index = 0; } ~container() { } // Returns the numbers of elements in the container int s
我在以下代码中遇到了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.cpp 1>e:avinashtesttesttest.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:avinashtesttesttest.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:avinashtesttesttest.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 ========== 解决方法
你需要改变这个:
int size() { return m_element_index; } 对此: int size() const { return m_element_index; } 告诉编译器你希望它允许在const实例上调用size(). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |