gpt4 book ai didi

c++ - 自定义 STL 容器包装器报告奇怪的编译器错误

转载 作者:行者123 更新时间:2023-11-28 08:23:25 27 4
gpt4 key购买 nike

我有一个 C++ 库(包含 50 多个源文件),它使用大量 STL 例程,主要容器是 listvector。这导致了巨大的代码膨胀,我想通过创建另一个本质上是包装器的库来减少代码膨胀在 listvector 上。

我基本上需要一个围绕 std::list 的包装器,它非常适合任何类型的列表容器。

下面显示的是我的列表包装器类。

template<typename T>
class wlist
{
private:
std::list<T> m_list;

public:

wlist();

typedef std::list<void*>::iterator Iterator;
typedef std::list<void*>::const_iterator CIterator;

unsigned int size () { return m_list.size(); }
bool empty () { return m_list.empty(); }
void pop_back () { m_list.pop_back(); }
void pop_front () { m_list.pop_front(); }
void push_front (const T& item) { m_list.push_front(item); }
void push_back (const T& item) { m_list.push_back(item); }
bool delete_item (void* item);
T& back () { return (m_list.empty()) ? NULL : m_list.back();}
T& front () { return (m_list.empty()) ? NULL : m_list.front();}
Iterator erase() { return m_list.erase(); }
Iterator begin() { return (Iterator) m_list.begin(); }
Iterator end() { return (Iterator) m_list.end(); }
};

文件1.h:

class label{

public:
int getPosition(void);
setPosition(int x);

private:
wlist<text> _elementText; // used in place of list<text> _elementText;

}

文件2.h:

class image {

private:

void draw image() {
//Used instead of list<label*>::iterator currentElement = _elementText.begin();
wlist<label*>::iterator currentElement = _elementText.begin();
currentElement->getPosition(); // Here is the problem.
currentElement ++;
}
}

使用以下错误消息调用 getPosition() 炸弹:

error: request for member `getPosition' in `*(&currentElement)->std::_List_iterator<_Tp>::operator-> [with _Tp = void*]()', which is of non-class type `void*'

getPosition() 类型转换为 label 类型无效。此外,我的迭代器是 void* 类型。

最佳答案

我认为问题是线

currentElement->getPosition();

不会工作,因为 currentElementvoid* 上的迭代器,而不是 label 上的迭代器。由于某些类型 T 上的迭代器表现得像 T*,这意味着你的 currentElement 迭代器表现得像一个 label**, 所以写上面的代码和写类似

(*currentElement).getPosition();

到这里,问题应该更容易看出来了——*currentElement是一个label*,而不是label,所以你不能在其上使用点运算符。

要解决此问题,请尝试将此代码更改为

((label *)(*currentElement))->getPosition();

这取消引用迭代器并类型转换 void* 以获取 label*,然后使用箭头运算符调用 getPosition()在指向的 label 上运行。

关于c++ - 自定义 STL 容器包装器报告奇怪的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4975356/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com