Ошибка no match for operator operand types are std

Given the following code;

#include<iostream>
using namespace std;

int main(){
    int number_1 = 3;
    int result_1 = 10;
    result_1 += number_1;
    cout << ++result_1;
    cout << result_1 += number_1;
}

The line cout << result_1 += number_1; giving me an error.

no match for ‘operator+=’ (operand types are ‘std::basic_ostream’ and ‘int’)

On the other hand, the cout << ++result_1; is running without any problems.

Can anyone please explain what is the error is for, what the cause is?

songyuanyao's user avatar

songyuanyao

168k16 gold badges305 silver badges400 bronze badges

asked Jul 27, 2016 at 10:49

herr_azad's user avatar

2

  1. Can anyone please explain what is the error is for, what the cause is?

According to Operator Precedence, operator<< has higher precedence than operator+=, so your code is equivalent as:

(cout << result_1) += number_1;

while cout << result_1 will return std::cout (i.e. std::ostream&) and then operator+= is attempted to be called on std::ostream and it doesn’t exist. That’s what the error message trying to tell you.

You could change it to:

cout << (result_1 += number_1) ;

or avoid such kind of confusing code fundamentally.

result_1 += number_1;
cout << result_1;
  1. On the other hand cout << ++result_1; is running with out any problem.

Beasuse operator++ has higher precedence than operator<<. So it’s equivalent as cout << (++result_1); and would be fine.

answered Jul 27, 2016 at 10:53

songyuanyao's user avatar

songyuanyaosongyuanyao

168k16 gold badges305 silver badges400 bronze badges

1

If you take a look at the operator precedence rules, you’ll find that the statement is equivalent to

(cout << result_1) += number_1 ;

The operator<< returns the std::cout. And there exists no std::ostream::operator+=(int).

Solution: Use parenthesis to express the intended order of operations.

On the other hand cout << ++result_1; is running with out any problem

As one would expect. Study the precedence of operators.

answered Jul 27, 2016 at 10:53

eerorika's user avatar

eerorikaeerorika

231k12 gold badges195 silver badges321 bronze badges

Read you commpiler error carefully. Everything is there :) .

The reason for error is operator precedence.
Compiler first executes cout << result_1.
Then, it tries to execute something like this: cout += number_1.

Does it have any sense?

To do what you intended change your line:

cout << (result_1 += number_1);

I strongly recommend reading this:
http://en.cppreference.com/w/cpp/language/operator_precedence

answered Jul 27, 2016 at 10:54

Lehu's user avatar

LehuLehu

7514 silver badges14 bronze badges

Operator precedence.

The call is semantically equivalent to something like cout << result_1; cout += result; — which is invalid.

Adding parentheses to the code (allowing the += computed before the <<) as follows allows the code to compile;

cout << (result_1 += number_1);

On the error itself; the compiler cannot find an implementation of the operator += for the arguments provided — there isn’t a standard one. This is because the cout << result_1 is evaluated before the operator +=. From the above, this makes sense, but doesn’t immediately indicate where the potential fix can be applied.

answered Jul 27, 2016 at 10:53

Niall's user avatar

NiallNiall

29.8k10 gold badges97 silver badges141 bronze badges

  • 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.

Ошибка на c=a-b;
Проблема с типами походу.
[Error] no match for ‘operator=’ (operand types are ‘massiv’ and ‘massiv’)
Не могу понять что он от меня хочет) Как исправить, подскажите добрые люди?

#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <iostream>
#pragma hdrstop

using namespace std;

class massiv
{	
private:
	int mas[5];
	int size=5;
public:
	massiv() 
	{
		for(int i=0;i<size;i++)
			mas[i]=0;
	}
	massiv(int len) 
	{
		if (len<1 || len>10) size=5;
			else size=len;	
		for(int i=0;i<size;i++)
			mas[i]=0;
	}
	massiv(massiv & w) 
	{
		size=w.size;
		for(int i=0;i<size;i++)
			mas[i]=w.mas[i];
	}
	~massiv()
	{
		
	}
	
	void vvod()
	{
		cout<<"vvedite massiv"<<endl;
		for(int i=0; i<size; i++)
		{
			cout<<i+1<<"= ";
			cin>>mas[i];
		}
	
	} 
	void print()
	{
		for(int i=0; i<size;i++){
			cout<<mas[i]<<" ";
		}
		cout << endl;
	}
	
	massiv operator-(massiv &w)
	{
		int temp;
		massiv c;
		if (size>w.size)
			temp=size;
		else
			temp=w.size;
			c.size=temp;
		for(int i=0;i<temp;i++)
		{
			if(i<size && i<w.size) 
			{
				c.mas[i]=mas[i]-w.mas[i];
			}
	
			if(i<size && i>=w.size) 
			{
				c.mas[i]=mas[i];
			}
	
			if(i>=size && i<w.size) 
			{
				c.mas[i]=-w.mas[i];
			}
		}
		return c;
	}
	
	massiv operator=(massiv &w)
	{
		for(int i=0;i<size;i++)
			mas[i]=w.mas[i];
		return *this;
	}
};

int main()
{
	massiv a,b,c; 
	a.vvod();
	b.vvod();
	cout<<endl;
	a.print();
	b.print();
	cout<<endl;
	c=a-b;<
	a.print();
	cout<<"-"<<endl;
	b.print();
	cout<<"="<<endl;
	c.print();
	return 0;
}

I’m getting a different error now.

In file included from toml11/toml/types.hpp:8:0,
                 from toml11/toml/parser.hpp:9,
                 from toml11/toml.hpp:36,
                 from toml-test.cpp:1:
toml11/toml/comments.hpp: In member function ‘toml::preserve_comments::iterator toml::preserve_comments::insert(toml::preserve_comments::const_iterator, const string&)’:
toml11/toml/comments.hpp:86:36: error: no matching function for call to ‘std::vector<std::basic_string<char> >::insert(toml::preserve_comments::const_iterator&, const string&)’
         return comments.insert(p, x);

xKore_Nano_Man

1 / 1 / 0

Регистрация: 30.12.2017

Сообщений: 101

1

31.12.2017, 21:59. Показов 14079. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Имеем следующий код:

C++
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
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
 
int main(int argc, char* argv[])
{
    cout<<"Write your name: "<<"n";
    string word;
    cin>>word;
    cout<<"How are you, "<<word<<"?"<<"n";
    cout<<"How old are you?"<<"n";
    string number;
    cin>>number;
    int old = 18;
    if(number < old);
    {
        cout<<"Sorry you don't have 18 years old!"<<"n";
    }
    else
    {
        cout<<"Welcome to the adult life, "<<word<<"n";
    }
}

При попытки запустить его у меня вылазит ошибка вот в этой строке: if(number < old); сама ошибка выглядит следующим образом: no match for ‘operator<‘ (operand types are ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ and ‘int’)|. Буду рад вашей помощи!) С наступающим)



0



Остап Бонд

Заблокирован

31.12.2017, 22:23

2

Лучший ответ Сообщение было отмечено xKore_Nano_Man как решение

Решение

xKore_Nano_Man, наверно надо строку

Цитата
Сообщение от xKore_Nano_Man
Посмотреть сообщение

string number;

при сравнении c ‘int old’ преобразовать в ‘int’?



1



1 / 1 / 0

Регистрация: 30.12.2017

Сообщений: 101

31.12.2017, 22:33

 [ТС]

3

Спасибо большое, переменную number нужно преобразовать в int…!!!!



0



зомбяк

1581 / 1215 / 345

Регистрация: 14.05.2017

Сообщений: 3,939

31.12.2017, 22:56

4

Цитата
Сообщение от xKore_Nano_Man
Посмотреть сообщение

string number;

int number;



0



1 / 1 / 0

Регистрация: 30.12.2017

Сообщений: 101

02.01.2018, 17:04

 [ТС]

5

Я знаю)



0



Понравилась статья? Поделить с друзьями:
  • Ошибка no module named numpy
  • Ошибка no main manifest attribute in jar
  • Ошибка no module named encodings
  • Ошибка no language file was founded
  • Ошибка no module named django