作为const传递给函数的对象返回指向其数据的指针,编译器会报错



我不需要修改数据…只需将其传递给需要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。

这个问题是因为我忘记了类实现的一些细节。版主可以删除它,因为它没有添加任何知识。

最新更新