【问题标题】:"Error: No operator "=" matches these operands" [closed]“错误:没有运算符“=”匹配这些操作数”[关闭]
【发布时间】:2013-04-09 10:40:26
【问题描述】:

我遇到了一个奇怪的问题,编译器突出显示“=”和“!=”作为错误,声称没有匹配的操作数,但我不知道如何。这是我的代码:

#pragma once
#include "Console.h"
#include "RandomNumber.h"
#include "Element.h"
#include "Flotsam.h"
#include "vector"
#include <list>
#include <iostream>

using namespace std;

#define NUMBER 10

int main()
{
    Console console;
    RandomNumber rnd;


    vector<Element*> flotsam;


    for(int i = 0; i < NUMBER; i++)
    {
        flotsam.push_back(new Element(rnd, console));
    }

    vector<Element>::iterator ptr;

    ptr = flotsam.begin();

    while(ptr!=flotsam.end())
    {
        ptr->printAt();
        ptr++; 
    }
    Sleep(1000);
    console.clear();

}

【问题讨论】:

  • vector&lt;Element*&gt; vs vector&lt;Element&gt;
  • 我应该提到,唯一突出显示的“=”和“!=”运算符位于“ptr”之后
  • 好的,我从vector中删除了指针,现在是“.”在 flotsam.pushback 处给出错误
  • 您需要添加指向迭代器声明的指针,或者如果您可以使用 C++11,只需使用 auto 关键字。 auto ptr = flotsam.begin().

标签: c++ vector operator-keyword operand


【解决方案1】:

你的向量有不同的类型,迭代器应该是

vector<Element*>::iterator ptr;
//            ^

【讨论】:

  • 谢谢,添加了那个指针。但现在这部分程序:ptr->printAt();给出错误:必须有指向类类型的指针
  • @user2288204 让(*ptr)-&gt;printAt()
  • 非常感谢大家,我的程序完美运行! :D
【解决方案2】:

flotsamstd::vector&lt;Element*&gt;,所以你需要

vector<Element*>::iterator ptr;

在通过迭代器访问指针时,您还需要取消对指针的引用:

(*ptr)->printAt();

或者,您可以通过使用Element 对象的向量来大大简化您的代码:

vector<Element> flotsam;

【讨论】:

    【解决方案3】:

    也许更好的解决方案是 (C++11):

    auto ptr = flotsam.begin();
    

    它对向量元素类型是稳定的。

    是的,看看你可能应该有的迭代器用法:

    vector<Element> flotsam;
    

    【讨论】:

      【解决方案4】:

      由于迭代器类型迭代vector&lt;Element&gt;flotsam 也应该是vector&lt;Element&gt;。这里显然不需要指针容器。对象容器似乎合适。要添加元素,只需使用pushback(Element(rnd, console));不需要new

      【讨论】:

      • 谢谢,我现在就修改 :)
      猜你喜欢
      • 2023-01-27
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多