无法将"this"指针从"const container"<T>转换为"container<T> &"
cannot convert 'this' pointer from 'const container<T>' to 'container<T> &'
我在下面的代码中得到以下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: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()
。
这里您将一个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;
}
您需要将size()
声明为const
方法:
int size() const {
return m_element_index;
}
因为在你的任务操作员
container& operator= (const container& other) { .... }
您正在调用other.size()
,而other
是reference-to-const
,这意味着您只能在其上调用const方法。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- std::p mr::memory_resource 如何与 std::container 产生性能差异?
- C++ "oldstyle container ":指针/数组/新 - 可能误会?
- 在其他容器中使用 boost::container::static_vector 时,GCC 编译错误"将'const s'绑定到类型's&'的引用丢弃限定符"
- 构造函数是否有一种现代C++方法来了解其'container'类?
- 为什么std::{container}::template不能推导其参数类型
- 如何显式调用运算符<<
- boost::container::vector 无法用谷物序列化?
- 如何从 boost::container::vector<std::string>::iterator 访问索引和对象?
- 模板化函数以从输入参数推断返回类型 stl-container
- 给定一个类型为 Container:<T>:Iterator 的函数参数,如何为某些类型的 T 实现特定的重载?
- boost::container::allocator_traits::is_partially_propagable是
- 模板操作员&lt;未打电话
- C / CUDA中的模板方法是3个角括号(&lt;&lt;&lt;)
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- C 建造者Clang STD :: Sill,找不到超载的操作员&lt;