我在以下代码中关注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 ==========
答案 0 :(得分:5)
你需要改变这个:
int size() {
return m_element_index;
}
到此:
int size() const {
return m_element_index;
}
告诉编译器您希望它允许在size()
实例上调用const
。
答案 1 :(得分:4)
在这里,您将const对象传递给赋值运算符:
container& operator= (const container& other) {
<...>
}
但是,在运营商内部,您正在调用other
的{{1}}功能:
size()
为了使用for ( int idx = 0; idx < other.size(); idx++)
对象可以使用,函数本身必须声明为const
:
const
答案 2 :(得分:3)
您需要将size()
声明为const
方法:
int size() const {
return m_element_index;
}
因为你的作业运算符
container& operator= (const container& other) { .... }
您正在呼叫other.size()
,而other
是reference-to-const
,这意味着您只能在其上调用const方法。