繁体   English   中英

不匹配operator =使用std :: vector

[英]no match for operator= using a std::vector

我有一个这样的类声明:

class Level
{
    private:
        std::vector<mapObject::MapObject> features;
    (...)
};

在其中一个成员函数中,我尝试迭代遍历该向量,如下所示:

vector<mapObject::MapObject::iterator it;
for(it=features.begin(); it<features.end(); it++)
{
    /* loop code */
}

这对我来说似乎很简单,但是g ++给了我这个错误:

src/Level.cpp:402: error: no match for 'operator=' in 'it = ((const yarl::level::Level*)this)->yarl::level::Level::features.std::vector<_Tp, _Alloc>::begin [with _Tp = yarl::mapObject::MapObject, _Alloc = std::allocator<yarl::mapObject::MapObject>]()'
/usr/include/c++/4.4/bits/stl_iterator.h:669: note: candidates are: __gnu_cxx::__normal_iterator<yarl::mapObject::MapObject*, std::vector > >& __gnu_cxx::__normal_iterator<yarl::mapObject::MapObject*, std::vector > >::operator=(const __gnu_cxx::__normal_iterator<yarl::mapObject::MapObject*, ``std::vector<yarl::mapObject::MapObject, std::allocator<yarl::mapObject::MapObject> > >&)

任何人都知道为什么会这样吗?

我猜这部分错误描述了你的问题:

(const yarl::level::Level*)this

成员函数是否在其中找到此代码的const限定成员函数? 如果是这样,您将需要使用const_iterator

vector<mapObject::MapObject>::const_iterator it;

如果成员函数是const限定的,那么只有成员向量上的begin()end()的const限定重载才可用,并且这两个都返回const_iterator

你在这里关闭了直角支架吗?

vector<mapObject::MapObject::iterator it;

如果你想要一个对象矢量,你的对象需要一个operator =。 MapObject有一个吗? 如果没有,请考虑一个指向MapObject的指针向量。

@James McNellis的回答(“绿色检查”最佳答案)用类似的描述修复了我的错误,但是我的错误是由@tmarthal提到他的回答帖子(没有定义赋值运算符)引起的。 他建议的修复是包含一个赋值运算符,但我只是想补充一点,我也能通过使用std :: vector <> :: const_iterator而不是std :: vector <> :: iterator修复此错误,对于没有赋值的类运算符已定义。 我不确定这是否真的是一个正确的解决方案,或者只是阻止编译器抱怨的东西。

如果我是你,我会检查mapObject :: MapObject是否有默认构造函数和公共赋值运算符。

在类标题的某处,你应该看到类似的东西:

public:
    MapObject();
    operator=(const MapObject &mapObject);

这意味着该类具有默认构造函数和赋值运算符。

使用没有默认构造函数的类无法实例化std :: vector,并且如果没有赋值运算符,则无法如上所述迭代该类。

因此,在类定义中添加赋值运算符,您的迭代将进行编译。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM