【问题标题】:Iterator no match operator= Error迭代器不匹配运算符=错误
【发布时间】:2011-07-19 17:00:28
【问题描述】:

我有 2 个类,即 classA 和 classB。在 classA 中有一个在堆内存上动态声明的映射。 然而,在 classB 中,正在尝试使用迭代器访问 classA 映射值。 不幸的是,我得到了迭代器的错误 no match operator= 。 如果我将地图移动到 B 类,迭代器将正常工作。有人可以帮助我吗,这一直困扰着我一段时间。 提前致谢。

class classA{
public:
  classA();
friend classB;
private:
  map <int,int>* _themap;
};

classA::classA(){
  _themap = new map<int,int>;
}

class classB{
private:
 classA* object = new classA();
 void accessthemap();
};

void classB::accessthemap(){

 map<int,int>::iterator it;
 it = object->_themap->begin();
 it = object->_themap->find();
}

【问题讨论】:

  • 让它object-&gt;_themap.begin()_themap 不是指针。
  • @n.m.这真的应该是一个答案,给你投票就好了,如果 superface 有机会接受答案(并关闭问题),那将是一件好事。
  • 首先,这段代码将如何编译?有很多错误,例如错误的类声明等
  • @cppcoder:这不是他要问的吗?
  • @Tomalak 他担心迭代器错误。而类本身有错误。我认为他可能已经监督了这一点。

标签: c++ iterator


【解决方案1】:

应该是

it = object->_themap.begin(); //not _themap->begin()

因为_themap 是一个非指针,所以你必须使用. 运算符,而不是-&gt; 运算符。

此外,还有一些错误。如果你把classA写成

//incorrect
classA{
   //...
};

应该是

//correct
class classA{
   //...
};

也就是说,您必须在类名之前使用关键字class。所以使用关键字class定义其他类,例如classB

【讨论】:

  • 假设我的语法在这种情况下都是正确的。当我尝试将迭代器分配给不同类的映射时,您知道为什么编译器仍然返回错误吗?
  • @superface:编译器仍然返回错误,因为您的假设 assuming my syntaxes are all correct in this case 不正确。
  • 为了避免对问题的进一步误解。我已经在代码块中编辑了语法。真正的问题在于它 = object->_themap->begin(); it = object->_themap->find();
【解决方案2】:

你不能在类定义中定义成员,所以这是错误的:

classB{
private:
 classA* object = new classA();
 void accessthemap();
};

而只是使用一个普通的对象(更不用说修复你的其他语法错误):

class classB {
private:
 classA object;
 void accessthemap();
};

这里不需要动态分配。

然后写object._themap.begin();

【讨论】:

    猜你喜欢
    • 2013-07-14
    • 1970-01-01
    • 2015-06-28
    • 2017-07-25
    • 1970-01-01
    • 2018-07-19
    • 2017-08-10
    • 2016-03-18
    • 2015-11-19
    相关资源
    最近更新 更多