作为const传递给函数的对象返回指向其数据的指针,编译器会报错
An object passed as const to a function returns a pointer to its data and the compiler complains
我不需要修改数据…只需将其传递给需要const版本数据的函数。
OtherList[i]->Data返回一个指针。如何让编译器平静下来?
template<class AnyVar>
void TypeLinkedList<AnyVar>::Insert (const TypeLinkedList<AnyVar>& OtherList, unsigned AtIndex)
{
const unsigned Len=OtherList.ListSize();
if (Len==0) return;
for (unsigned i=0;i<Len;i++) {Insert(OtherList[i]->Data,AtIndex++);}
}
编辑:错误信息
error: passing 'const TypeLinkedList<float>' as 'this' argument of 'TypeNode<AnyVar, 2u>* TypeLinkedList<AnyVar>::operator[](unsigned int) [with AnyVar = float]' discards qualifiers [-fpermissive]|
函数声明如下:
void Insert (const AnyVar& Value, unsigned AtIndex=0);
void Insert (const TypeLinkedList<AnyVar>& OtherList, unsigned AtIndex);
TypeNode<AnyVar,2>* operator[] (const unsigned idx){if (idx<Size) return NodeAt(idx); else if (Size==0) return nullptr; else return NodeAt(Size-1);}
编辑2:有人建议用const重载操作符[],但这也行不通:
const TypeNode<AnyVar,2>* operator[] (const unsigned idx) const {if (idx<Size) return NodeAt(idx); else if (Size==0) return nullptr; else return NodeAt(Size-1);}
错误:error: passing 'const TypeLinkedList<float>' as 'this' argument of 'TypeNode<AnyVar, 2u>* TypeLinkedList<AnyVar>::NodeAt(unsigned int) [with AnyVar = float]' discards qualifiers [-fpermissive]|
在您的TypeLinkedList
模板类中没有operator[]
的const
过载。提供一个,你就会得到解决:
template<class AnyVar>
void TypeLinkedList<AnyVar>::operator[](unsigned AtIndex) { ... }
template<class AnyVar>
void TypeLinkedList<AnyVar>::operator[](unsigned AtIndex) const { ... }
// ^^^^^
顺便说一句,你的函数没有多大意义。对于容器类型,insert
函数可能应该只接受元素,而不是传递其他容器和该容器中的索引。
如我所料:TypeLinkedList的下标操作符[]对const没有重载。没有边界检查的简单重载示例:
#include <iostream>
template<class T>
class Test
{
public:
T& operator[](std::size_t idx) { return m_data[idx]; }
const T& operator[](std::size_t idx) const { return m_data[idx]; }
private:
T *m_data = new T[10];
};
main(){
Test<int> t1;
const Test<int> t2;
std::cout << t1[0] // calls first non const method
<< t2[0]; // calls second const method
}
请不要介意。我很抱歉把你们都牵扯进来。
操作符[]使用NodeAt()函数,节点at函数需要修改列表。有一个书签功能,每次查询都会更新。每次我们索引到某个地方,书签都会改变。因此我根本不能使用const,我必须回滚到plain。
这个问题是因为我忘记了类实现的一些细节。版主可以删除它,因为它没有添加任何知识。
相关文章:
- 检查输入 std::array 指针数据是否等于某个常量数组
- 指针数据类型变量如何包含对象?
- 如何在C++中使用类对象访问指针数据成员
- 如何强制实施有关指针数据成员的常量正确性
- 为什么指针>数据有效,而 *double_pointer->data 不起作用?
- 如何从C++中的原始指针数据构造张量流::张量
- 检查课程是否具有指针数据成员
- 处理类的指针数据成员的动态内存
- 在堆上启动的指针数据成员
- 具有指针数据类型的非类型函数模板参数
- 如何将复杂的指针数据作为属性放入qt-plugin-xml文件中
- C++指向函数作为参数的指针.数据类型不兼容
- 初始化指针数据结构的空间复杂性
- 运算符重载与 C++ : 具有指针数据成员的类
- 我是否需要清理非指针数据成员
- 在堆或堆栈上的指针类实例中分配C++非指针数据成员
- 函数结束后丢失指针数据
- C++ 如何确保复制构造函数不会修改原始对象的指针数据成员?
- 为什么从派生类访问基类的数据时会返回无意义的数据(我认为是指针数据)
- 将原始鼠标/指针数据转换为有意义的内容