Error no match for operator operand types are std istream

  • Forum
  • Beginners
  • no match for operator>>

no match for operator>>

Hi, so I’m a total beginner and am having trouble trying to overload the insertion operator. When I try it tells me «error: no match for ‘operator>>’ (operand types are ‘std::istream’ {aka ‘std::basic_istream’} and ‘int’)»

Here is the header:

1
2
3
4
5
6
7
8
9
10
11
12
  #include <iostream> 
using namespace std;

class myArray {
    public:
    myArray(int len = 0);
    int operator[](int i) { return a[i]; }
    friend istream& operator>> (istream &in,  myArray &x);
    private:
    int arrayLen;
    int a[];
};

And this is the implementation file:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> 
#include "myArray.h"
using namespace std;

myArray::myArray(int len){
    arrayLen = len;
}

myArray::istream& operator>> (istream &in,  myArray &x)
{
    in >> x.a;
    return in;
}

I assume that I have a type mismatch, but I guess I’m a little thick, because I don’t see it.

What do YOU think line 11 is doing in the 2nd one?
How big do you think that A array is?

you cannot cin an array. you have to loop and read one by one.
and C style arrays need a fixed size at compile time; the only way around this is a pointer of some sort (whether done for you or not).

edit, misread what you did, the >> is fine apart from trying to read and write an array.

Last edited on

There are three main issues with your code.

The first issue is that your array a is not specified as having any size. The size of arrays, whether in a class or not, must be known at compile time.

The second issue is second snippet, line 9: myArray::istream& is not a type. You meant to just write istream&.

The third issue is second snippet, line 11: You are calling >> on an array (a). Presumably you meant to call something more like:

1
2
in >> x.a[arrayLen];
arrayLen++;

You should also be thinking about bounds checking, e.g. (if arrayLen == maxSize) { don’t add to array }. This is assuming you have some notion of «MaxSize» (see first issue).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>

using namespace std;

constexpr int MaxSize = 1000;

class myArray {
public:
    myArray(int len = 0);
    int operator[](int i) const { return array[i]; }
    friend istream& operator>> (istream &in,  myArray &x);
    
    //private: // making public for demonstration
    int arrayLen;
    int array[MaxSize];
};

myArray::myArray(int len)
: arrayLen(len) {

}

istream& operator>> (istream &in,  myArray &arr)
{
    if (arr.arrayLen < MaxSize)
    {
        in >> arr.array[arr.arrayLen];
        arr.arrayLen++;
    }

    return in;
}

int main()
{
    myArray myArr;
    std::cin >> myArr >> myArr >> myArr;

    for (int i = 0; i < myArr.arrayLen; i++)
    {
        std::cout << myArr.array[i] << 'n';
    }
}

Last edited on

So does that mean that I could do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream> 
#include "myArray.h"
using namespace std;


myArray::myArray(int len)
{
arrayLen=len;
}

istream& operator>> (istream &in,  myArray &arr)
{
    if (arr.arrayLen < MaxSize)
    {
        in >> arr.array[arr.arrayLen];
        arr.arrayLen++;
    }

    return in;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> 
using namespace std;

constexpr int MaxSize = 1000;

class myArray {
    public:
    myArray(int len = 0);
    int operator[](int i) { return array[i]; }
    friend istream& operator>> (istream &in,  myArray &x);
    private:
    int arrayLen;
    int array[MaxSize];
};

Wait, no, that still doesn’t work… Okay, I still seem to be misunderstanding something.

What does «not work» mean?

The same error comes up about «no match for ‘operator>>’ (operand types are ‘std::istream’ {aka ‘std::basic_istream’} and ‘int’)»

Perhaps something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

constexpr size_t MaxSize {1000};

class myArray {
public:
	myArray() {}
	size_t size() const { return arrayLen; }

	int operator[](size_t i) { return array[i]; }
	const int operator[](size_t i) const { return array[i]; }
	friend std::istream& operator>> (std::istream& in, myArray& x);

private:
	size_t arrayLen {};
	int array[MaxSize] {};
};

std::istream& operator>> (std::istream& in, myArray& arr) {
	if (arr.arrayLen < MaxSize)
		in >> arr.array[arr.arrayLen++];

	return in;
}

int main() {
	myArray myArr;

	std::cin >> myArr >> myArr >> myArr;

	for (size_t i {}; i < myArr.size(); ++i)
		std::cout << myArr[i] << 'n';
}

person5273, your code that you have shown does not have problems, assuming it’s being successfully compiled/linked by however you are building it. I was able to copy and paste it into cpp.sh as one file and compile it (after removing the #include «myArray.h»), after adding a main function. So the problem exists in part of the code you are not showing.

The array size is specified at compile time.

Topic archived. No new replies allowed.

  • Remove From My Forums
  • Question

  • i need overload somethings, in a class, but i don’t understand how:(

    like the string and cin (‘>>’)

Answers

  • i need overload somethings, in a class, but i don’t understand how:(

    like the string and cin (‘>>’)

    • Marked as answer by

      Sunday, September 8, 2013 6:08 PM

  • «C:UsersJoaquimDocumentsCodeBlockstesteventstest.h|50|error: ‘istream’ does not name a type|»

    i have the ‘#include <iostream>’ in code

    Add «using namespace std;» after the #includes, or else refer to the class by its full name, std::istream


    Igor Tandetnik

    • Marked as answer by
      Cambalinho
      Sunday, September 8, 2013 6:08 PM

  • I think you are looking for something like this:

    friend istream &operator>>( istream  &input, property &d )
          {
             ValueType v;
             input >> v;
             d = v;
             return input;
          }
    

    Igor Tandetnik

    • Marked as answer by
      Cambalinho
      Friday, September 6, 2013 10:19 PM

  • hpp
    ~~~
    namespace abc
    class Address{
    ....
       friend std::ostream& operator<<( std::ostream& os, const abc::Address& obj );
       friend std::istream& operator>>( std::istream& is, abc::Address& obj );
    }; //class
    } //namespace
    
    cpp
    ~~
    
    namespace abc{
    std::ostream& operator<<( std::ostream& os, const abc::Address& obj ) {
        return os << obj.getUnitNumber() << " "
               << obj.getStreetName ()   << " "
               << obj.getCity()          << " "
               << obj.getProvince()      << " "
               << obj.getPostalCode()    << " "
               << obj.getCountry()       << " ";
    
    }
    std::istream& operator>>( std::istream& is, abc::Address& obj ) {
        std::string t;
        is >> t;
        obj.setUnitNumber(t);
        t.clear();
        is.ignore(1);
    
        is >> t;
        obj.setStreetName(t);
        t.clear();
        is.ignore(1);
    
        is >> t;
        obj.setCity(t);
        t.clear();
        is.ignore(1);
    
        is >> t;
        obj.setProvince(t);
        t.clear();
        is.ignore(1);
    
        is >> t;
        obj.setPostalCode(t);
        t.clear();
        is.ignore(1);
    
        is >> t;
        obj.setCountry(t);
    
        return is;
    
    }

    Check out this code, it shows all you need to know an great detail;

    • Marked as answer by
      Cambalinho
      Sunday, September 8, 2013 6:08 PM

  • «hello » and «world» are both char* pointers (well, to be precise, they are of type const char[7] and const char[6], correspondingly). It is impossible to modify how an operator works on operands that are built-in types; you can only overload an operator
    where at least one operand is of a user-defined type (a class or an enum).


    Igor Tandetnik

    • Marked as answer by
      Cambalinho
      Sunday, September 8, 2013 6:08 PM

  • Well, you can write a named function:

    string concat(const char* a, const char* b) {
      return string(a) + b;
    }
    
    string a = concat("hello ", "world");
    

    Igor Tandetnik

    • Marked as answer by
      Cambalinho
      Sunday, September 8, 2013 6:07 PM

Привет, я пытаюсь распечатать список целых чисел, и я продолжаю получать эту ошибку.

У меня есть структура, в которой есть список.

struct faceFiguration{

    int faceID;
    list<int> setofVertices;

};

И у меня есть список этой структуры

 list<faceFiguration> pattern;

И вот где я запутался, я попытался распечатать здесь списки:

void PrintFaces(){

      currentFace = pattern.begin();
      while(currentFace != pattern.end()){

        cout << currentFace -> faceID << endl;

        for(auto currentVertices = currentFace->setofVertices.begin(); currentVertices != currentFace->setofVertices.end(); currentVertices++){

          cout << currentVertices;

        }

        cout << 'n';
        currentFace++;
      }

    }

Это полное сообщение об ошибке

error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘std::__cxx11::list<int>’)

4 ответа

Лучший ответ

currentVertices здесь итератор. Это объект, который действует как указатель. Вы не можете распечатать его с помощью cout. Но да, вы можете распечатать значение, на которое указывает итератор. Для этого вы должны поставить * перед итератором. То есть *currentVertices. (Читается как content of currentVertices)

Итак, резюме

  1. currentVertices — это итератор (или указатель, если хотите), а *currentVertices — это content of that iterator.
  2. Вам нужно cout content of iterator, а не iterator

Я не думаю, что сообщение об ошибке действительно относится к строке, которая вызывает здесь проблему (вы пробовали << — добавить сам список раньше?), Но

cout << currentVertices;

Пытается вызвать operator << со ссылкой std::ostream (std::cout) и итератором в std::list. Это не работает, потому что тип итератора не имеет этого оператора (зачем он). Однако итераторы моделируются после указателей и, следовательно, позволяют разыменовывать для доступа к элементу, на который они ссылаются. Короче; это должно работать:

cout << *currentVertices;

Где * перед currentVertices обозначает разыменование и дает int& (ссылку на базовый элемент списка).


1

lubgr
2 Мар 2021 в 06:31

Вы уже получили ответы о разыменовании итератора:

for(auto currentVertices = currentFace->setofVertices.begin();
    currentVertices != currentFace->setofVertices.end();
    currentVertices++)
{
    cout << *currentVertices;   // dereference
}

Однако вы можете сделать это автоматически, используя цикл for на основе диапазона:

for(auto& currentVertices : currentFace->setofVertices) {
    cout << currentVertices;    // already dereferenced
}


1

Ted Lyngmo
2 Мар 2021 в 07:12

Как уже упоминалось другими

 cout << currentVertices;

Пытается напечатать итератор. Но нет перегрузки для operator<<, которая принимает второй параметр этого типа. Либо разыменовать итератор

 //      V
 cout << *currentVertices;

Или упростить весь цикл:

for(const auto &currentVertices : currentFace->setofVertices){
    cout << currentVertices;
}


0

churill
2 Мар 2021 в 07:12

Понравилась статья? Поделить с друзьями:
  • Error no configured target data sources
  • Error no communication with vmc
  • Error no browser servers found
  • Error no available storage method found
  • Error nginx restart failed