No match for operator c как исправить

void read(double *a,double *b)
{
    double c,d;
    cout<<"Enter the 2 no.";
    cin>>c>>d;
    a=c;
    b=d;
}

This won’t work, because you want to change the values pointed to by the pointers, not the pointer itself, result in the error. Fix it to this:

void read(double *a,double *b)
{
    double c,d;
    cout<<"Enter the 2 no.";
    cin>>c>>d;
    *a=c;
    *b=d;
}

Of course, in such a case, I wouldn’t recommend using pointers, better to use references, so no dereferencing is required, and you can call it like read(a,b):

void read(double &a,double &b)
{
    double c,d;
    cout<<"Enter the 2 no.";
    cin>>c>>d;
    a=c;
    b=d;
}

The double& b notation means pass-by-reference. You also have the same problem for your other read function, fix it to this:

void read(double *a,double *b)
{
    cout<<"Enter the 2 no.";
    cin>>*a>>*b;
}

or better:

void read(double &a,double &b)
{
    cout<<"Enter the 2 no.";
    cin>>a>>b;
}

Ошибка на 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;
}

  

The 'No match for operator<<' error in C++ usually occurs when you try to use the `<<` operator with an object for which the operator<< is not defined or overloaded. In this guide, we will discuss the causes of this error and provide step-by-step solutions to resolve it. 

## Table of Contents

- [Understanding the operator<< in C++](#understanding-the-operator-in-c)
- [Common causes of the 'No match for operator<<' error](#common-causes-of-the-no-match-for-operator-error)
- [Step-by-step guide to resolving the error](#step-by-step-guide-to-resolving-the-error)
- [FAQ](#faq)

<a name="understanding-the-operator-in-c"></a>
## Understanding the operator<< in C++

In C++, the `<<` operator is used for various purposes, such as:

- As a bitwise left shift operator for integral types
- As an insertion operator for streams (like `std::ostream`)

For example, when using `std::cout` to print values to the console, you are actually using the overloaded `<<` operator for `std::ostream`.

```cpp
#include <iostream>

int main() {
    int num = 42;
    std::cout << "The answer is: " << num << std::endl;
    return 0;
}

Common causes of the ‘No match for operator<<‘ error

Here are some common causes of the ‘No match for operator<<‘ error:

  1. Attempting to use the << operator with a custom class or struct without overloading it
  2. Forgetting to include the required header files
  3. Using the wrong namespace

Step-by-step guide to resolving the error

Step 1: Overload the operator<< for your custom class or struct

To resolve the ‘No match for operator<<‘ error, you need to overload the << operator for your custom class or struct. Here’s an example:

#include <iostream>

class MyClass {
public:
    int value;

    MyClass(int v) : value(v) {}
};

std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
    os << "MyClass value: " << obj.value;
    return os;
}

int main() {
    MyClass obj(42);
    std::cout << obj << std::endl;
    return 0;
}

Ensure that you have included the necessary header files, such as <iostream> for using std::cout and the << operator for streams.

Step 3: Ensure that you are using the correct namespace

Make sure you are using the correct namespace, such as std for standard library functions and classes:

using namespace std;

FAQ

Q1: Can I overload the operator<< for built-in types like int or float?

No, you cannot overload the << operator for built-in types like int or float. The standard library already provides overloads for these types.

Q2: How do I overload the operator<< for a template class?

To overload the << operator for a template class, you can define the operator as a template function:

template<typename T>
std::ostream& operator<<(std::ostream& os, const MyTemplateClass<T>& obj) {
    os << "MyTemplateClass value: " << obj.value;
    return os;
}

Q3: What if I want to use the operator<< with a pointer to an object?

If you want to use the << operator with a pointer to an object, you need to overload the operator for pointers:

std::ostream& operator<<(std::ostream& os, const MyClass* obj) {
    os << "MyClass value: " << obj->value;
    return os;
}

Q4: Can I overload the operator<< as a member function of my class?

No, you cannot overload the << operator as a member function of your class. The left-hand operand of the << operator is a stream (like std::ostream), and you cannot add member functions to stream classes.

Q5: Can I use the operator<< with other stream classes like std::ofstream?

Yes, you can use the << operator with other stream classes like std::ofstream. You just need to include the appropriate header file (like <fstream> for std::ofstream) and make sure your overloaded operator works with the base std::ostream class.

  • C++ Operators Overloading
  • C++ I/O Streams
  • C++ Namespaces
    «`
  • 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.

Маринчик

0 / 0 / 3

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

Сообщений: 150

1

18.05.2014, 17:36. Показов 13533. Ответов 4

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


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

во всей программе выбивает только одну ошибку.. надоел этот вопрос но что не так????????
92 no match for ‘operator=’ in ‘P3 = operator<(matr&, matr&)(((matr&)(&P2)))’

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include<iostream>/*zagolovochnij fajl s klassami, funktsijami i peremennimi dlja organizacii vvoda-vivoda v jazike programmirovaniya C++*/
/*#include <stdlib.h>*/
using namespace std;/*ob'javlenie prostranstva imen  std.*/
 
class matr
{ public:
  float  *x;
  int n,m;
  public:
  matr(int, int);
  matr (matr& f);
  void vvod();
  void ww();
  friend matr  operator+(matr& ob1, matr& ob2);
  matr&  operator=(matr& ob2);
  ~matr();
};
//==============================================
//konstryktor s parametrami
matr::matr(int _n, int _m)
{    n=_n; m=_m;
     x=new float [n*m];
     puts("n konstryktor ");
}
//==============================================
//konstryktor kopii
matr::matr(matr& f)
  {
  n=f.n;
  m=f.m;
  x=new float [n*m];
 for(int i=0; i<n; i++)
 for(int j=0; j<m; j++)
*(x+i*m+j)=*(f.x+i*f.m+j);
  cout <<" rabotal konstryktor kopii  ";
  }
//==============================================
 
void matr::vvod()
{
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
*(x+i*m+j)=rand() % 101 - 50;
}
//==============================================
 
matr::~matr ()
{
delete[]x;
puts("n rabotal destryktor");
}
//==============================================
 
matr  operator<(matr& P1, matr& P2)
{
matr rez(P1.n, P1.m);
puts("n rez dla + ");
for(int i=0;i<rez.n;i++)
for(int j=0;j<rez.m;j++)
*(rez.x +i*rez.m+j)=*(P1.x+i*P1.m+j)+*(P2.x+i*P2.m+j);
return rez;
}
//==================================
matr& matr::operator=(matr& P2)
{
matr rez(P2.m,P2.n);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
*(x+i*m+j)=*(P2.x+i*P2.m+j);
return * this;
}
//==================================
void matr::ww()
{
for(int i=0;i<n;i++)
{
cout<<"n" ;
for(int j=0;j<m;j++)
cout<< *(x+i*m+j)<<"  "; }
}
//==================================
 
int main()
{
matr P1(3,4);
P1.vvod();
P1.ww();
matr P2(3,4);
P2.vvod();
P2.ww();
matr P3(3,4);
P3=P1<P2;
P3.ww();
}



0



Модератор

Эксперт С++

13100 / 10373 / 6206

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

Сообщений: 27,739

18.05.2014, 18:07

2

VS 2008 компилирует без ошибок.
Может важно, что в функции operator= написано return * this;
а не return *this; (без пробела)



1



0 / 0 / 3

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

Сообщений: 150

18.05.2014, 18:42

 [ТС]

3

а мы в Dev-C++ работаем. и у меня выбивает ошибку((((



0



1500 / 1146 / 165

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

Сообщений: 2,279

18.05.2014, 18:58

4

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

Решение

а зачем у вас конструктор копирования, оператор = и прочие принимают неконстантную ссылку?
в этих функциях передаваемые объекты меняются? нет. значит нужно константную.
в вашем случае идет попытка вызова оператора =, которому передается временный объект (результат оператора <).
неконстантные ссылки не строятся из временных объектов. это запрещено. кстати, студия такую ошибку почему-то
не считает за ошибку.
короче, сделайте все аргументы своих функций константными ссылками, если внутри функций передаваемый
объект не изменяется.



1



zss

Модератор

Эксперт С++

13100 / 10373 / 6206

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

Сообщений: 27,739

18.05.2014, 19:06

5

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

Решение

Ссылки надо сделать константными в равно и в копиконструкторе

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//konstryktor kopii
matr::matr(const matr& f)
  {
  n=f.n;
  m=f.m;
  x=new float [n*m];
 for(int i=0; i<n; i++)
 for(int j=0; j<m; j++)
*(x+i*m+j)=*(f.x+i*f.m+j);
  cout <<" rabotal konstryktor kopii  ";
  }
//==================================
matr& matr::operator=(const matr& P2)
{
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
*(x+i*m+j)=*(P2.x+i*P2.m+j);
return *this;
//  ???????????? что будет, если размерности разные  ???????????
}



1



Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти дробь от дроби видео
  • Ошибка неверный образ как исправить
  • Как найти соотношение объемов конусов
  • Как найти календарь на айфоне
  • Как найти корпус пистолета пулемета в раст

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии