Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / C++ [игнор отключен] [закрыт для гостей] / Перегрузка оператора "==" и "=" / 5 сообщений из 5, страница 1 из 1
12.03.2018, 23:25
    #39613832
Iridze
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Перегрузка оператора "==" и "="
Писала программу для сложения/ вычитания/умножения матриц в которые надо было посылать разные типы. Для int все работало float, но надо было ее добавить тип простая дробь.
Не могу реализовать перегрузки операторов "==" и "=".
"=" пыталась перегрузить, но как-то криво вышло
Еще есть проблемка с оператора %. Я его перегрузила, но не могу понять как его реализовать с float

В общем у меня выдает три ошибки:
бинарный "==": не найден оператор, принимающий левый операнд типа "drobi" (или приемлемое преобразование отсутствует)
бинарный "=": не найден оператор, принимающий правый операнд типа "int" (или приемлемое преобразование отсутствует)
%: недопустимо, левый операнд имеет тип "float"

Очень нужна помощь с решением этих проблем.

Header.h

Код: plaintext
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.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
#ifndef Array_h
#define Array_h

#include <iostream>

using namespace std;

class drobi {

private:
	int chislitel, znamenatel;

public:
	drobi(int chisl, int zn)
	{
		chislitel = chisl;
		znamenatel = zn;
	}
	drobi()
	{
		chislitel = 0;
		znamenatel = 0;
	}


	void set()
	{
		int NOD = 0;
		if (chislitel>znamenatel) NOD = znamenatel; else NOD = chislitel;
		for (int i = NOD; i>0; i--)
		{
			if ((fmod(chislitel, i) == 0) && (fmod(znamenatel, i) == 0))
			{
				chislitel = chislitel / i;
				znamenatel = znamenatel / i;
			}
		}

	}

	void sett()
	{
		int cell;
		int c = chislitel;
		int z = znamenatel;
		if ((chislitel > znamenatel) && znamenatel != 1)
		{
			cell = c / z;
			c = c % z;
			cout << "OR";
			cout << '\t' << '\t' << '\t';
			cout << cell << " " << c << "/" << z;
		}
		if (znamenatel > chislitel)
		{
			z = z / c;
			c = c / c;
			cout << "OR";
			cout << '\t' << '\t' << '\t';
			cout << c << "/" << z;

		}
		if (znamenatel == 1) {
			cout << "OR";
			cout << '\t' << '\t' << '\t';
			cout << c;
		}

		else cout << " ";
	}

	drobi operator+(drobi dr)
	{
		int ymn;
		if (znamenatel != dr.znamenatel)
		{
			ymn = znamenatel;
			znamenatel = znamenatel * dr.znamenatel;
			chislitel = chislitel * dr.znamenatel;
			dr.chislitel = dr.chislitel*ymn;
			dr.znamenatel = znamenatel;
		}
		int x = chislitel + dr.chislitel;
		cout << "The sum of two fractions: ";
		return drobi(x, znamenatel);
	}

	drobi operator-(drobi dr)
	{
		int ymn;
		if (znamenatel != dr.znamenatel)
		{
			ymn = znamenatel;
			znamenatel = znamenatel * dr.znamenatel;
			chislitel = chislitel * dr.znamenatel;
			dr.chislitel = dr.chislitel*ymn;
			dr.znamenatel = znamenatel;
		}
		int x = chislitel - dr.chislitel;
		cout << "Fraction minus the fraction: ";
		return drobi(x, znamenatel);
	}

	friend drobi operator%(drobi dr, int ymn)
	{
		if ((dr.chislitel % ymn == 0) && (dr.znamenatel % ymn == 0))
		{
			int x = dr.chislitel;
			int y = dr.znamenatel;
			return drobi(x, y);
		}

	}

	drobi operator*(drobi dr)
	{
		int x = chislitel * dr.chislitel;
		int y = znamenatel * dr.znamenatel;
		cout << "The product of two fractions: ";
		return drobi(x, y);
	}
	friend drobi operator*(drobi dr, int z)
	{
		int x = dr.chislitel *z;
		int y = dr.znamenatel;
		return drobi(x, y);
	}


	friend ostream& operator<<(ostream& stream, const drobi& obj)
	{
		stream << obj.chislitel << "/";
		stream << obj.znamenatel << endl;
		return stream;
	}

	friend istream& operator>>(istream& stream, drobi& obj)
	{
		stream >> obj.chislitel;
		stream >> obj.znamenatel;
		return stream;
	}


};

template<typename T> class arrr
{

	template <typename T>
	friend arrr<T> operator+ (arrr<T> &m1, arrr<T> &m2);
	template <typename T>
	friend arrr<T> operator- (arrr<T> &m1, arrr<T> &m2);
	template <typename T>
	friend arrr<T> operator* (arrr<T> &m1, arrr<T> &m2);


	friend istream &operator>>(istream &istr, arrr &k)
	{
		for (int i = 0; i<k.n; i++)
			for (int j = 0; j<k.m; j++)
				istr >> k(i, j);
		return(istr);
	}

	friend ostream &operator<<(ostream &ostr, arrr &k)
	{
		for (int i = 0; i<k.n; i++)
		{
			for (int j = 0; j<k.m; j++)
				ostr << k(i, j) << "\t";
			ostr << "\n";
		}
		return(ostr);
	}
private:
	int n, m;
	T **value;
public:

	T & operator()(int n, int m);
	drobi operator=(const drobi other);

	arrr(int no, int mo) {
		n = no;
		m = mo;
		value = new T *[n];
		for (int i = 0; i < n; i++)
			value[i] = new T[m];
	}

	arrr()
	{
		n = 0;
		m = 0;
	}

	class error {};
};

template <typename T> drobi arrr<T>::operator =(drobi other)
{
	if (this != &other)
	{
		this->chislitel = other.chislitel;
		this->znamenatel = other.znamenatel;
	}
	return *this;
}

template <typename T> arrr<T> operator+(arrr<T>& m1, arrr<T>& m2)
{
	if (m1.n == m2.n && m1.m == m2.m)
	{
		arrr<T> temp(m1.n, m1.m);
		for (int i = 0; i < m1.n; i++)
			for (int j = 0; j < m1.m; j++)
				temp(i, j) = m1(i, j) + m2(i, j);
		return(temp);
	}
	else throw arrr<T>::error();
}

template <typename T> arrr<T> operator-(arrr<T>& m1, arrr<T>& m2)
{
	if (m1.n == m2.n && m1.m == m2.m)
	{
		arrr<T> temp(m1.n, m1.m);
		for (int i = 0; i < m1.n; i++)
			for (int j = 0; j < m1.m; j++)
				temp(i, j) = m1(i, j) - m2(i, j);
		return(temp);
	}
	else throw arrr<T>::error();
}

template <typename T> arrr<T> operator*(arrr<T>& m1, arrr<T>& m2)
{
	if (m1.n == m2.m)
	{
		arrr<T> temp2(m1.n, m1.m);
		for (int i = 0; i < m1.n; i++)
		{
			for (int j = 0; j < m2.m; j++)
			{
				temp2(i, j) = 0;
				for (int k = 0; k < m1.m; k++)
					temp2(i, j) = temp2(i, j) + (m1(i, k) * m2(k, j));
			}
		}
		return(temp2);
	}
	else throw arrr<T>::error();

}


template <typename T> void min(arrr<T>& value, int n, int m)
{
	int i = 0, j = 0;
	T min = value(i, j);

	for (i = 0; i < n; i++)
	{
		for (j = 0; j < m; j++)
		{
			if (min >= value(i, j))
			{
				min = value(i, j);
			}
		}
	}
	cout << min << "\t";

}


template <typename T> T& arrr<T>::operator()(int n, int m)
{
	return (value[n][m]);
}

template <typename T> static void parn(arrr<T>& value, int n, int m)
{
	int i, j;
	for (i = 0; i < n; i++)
	{
		for (j = 0; j < m; j++)
		{
			T u = value(i, j);
			if (u % 2 == 0)
			{
				value(i, j) = value(i, j) * 3;

			}
			cout << value(i, j) << "\t";
		}
		cout << "\n";
	}

}

#endif



7.cpp

Код: plaintext
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.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
#include "stdafx.h"
#include <iostream>
#include "Header.h"

using namespace std;

void PlayINT(int n, int m, int n1, int m1)
{
	arrr<int> a(n, m);
	arrr<int> b(n1, m1);
	arrr<int> c;
	arrr<int> d;
	arrr<int> z;

	cout << "enter matrix A:\n";
	cin >> a;
	cout << "enter matrix B:\n";
	cin >> b;
	cout << "MIN A: ";
	min(a, n, m);
	cout << "\n";
	cout << "MIN B: ";
	min(b, n1, m1);
	cout << "\n";
	try {
		c = a + b;
		cout << "sum of two matrices A and B :\n" << c;
	}
	catch (arrr<int>::error) {
		cout << "error: the sizes of summable matrices must coincide " << endl;
	}
	try {
		d = a - b;
		cout << "subtraction of two matrices A and B:\n" << d;
	}
	catch (arrr<int>::error)
	{
		cout << "error:the sizes of matrices must coincide" << endl;
	}
	try {
		z = a * b;
		cout << "multiplication of two matrices A and B:\n" << z;
	}
	catch (arrr<int>::error)
	{
		cout << "error: the number of columns of the first matrix must coincide with the number of rows of the second matrix" << endl;
	}
	cout << "All items with paired values are increased three times, matrice A:" << endl;
	parn(a, n, m);
	cout << "All items with paired values are increased three times, matrice B:" << endl;
	parn(b, n1, m1);
}

void PlayDROBI(int n, int m, int n1, int m1)
{
	arrr<drobi> a(n, m);
	arrr<drobi> b(n1, m1);
	arrr<drobi> c;
	arrr<drobi> d;
	arrr<drobi> z;

	cout << "enter matrix A:\n";
	cin >> a;
	cout << "enter matrix B:\n";
	cin >> b;
	cout << "MIN A: ";
	//min(a, n, m);
	//cout << "\n";
	//cout << "MIN B: ";
	//min(b, n1, m1);
	//cout << "\n";
	try {
		c = a + b;
		cout << "sum of two matrices A and B :\n" << c;
	}
	catch (arrr<drobi>::error) {
		cout << "error: the sizes of summable matrices must coincide " << endl;
	}
	try {
		d = a - b;
		cout << "subtraction of two matrices A and B:\n" << d;
	}
	catch (arrr<drobi>::error)
	{
		cout << "error:the sizes of matrices must coincide" << endl;
	}
	try {
		z = a * b;
		cout << "multiplication of two matrices A and B:\n" << z;
	}
	catch (arrr<drobi>::error)
	{
		cout << "error: the number of columns of the first matrix must coincide with the number of rows of the second matrix" << endl;
	}
	cout << "All items with paired values are increased three times, matrice A:" << endl;
	parn(a, n, m);
	cout << "All items with paired values are increased three times, matrice B:" << endl;
	parn(b, n1, m1);
}
void PlayFloat(int n, int m, int n1, int m1)
{
	arrr<float> a(n, m);
	arrr<float> b(n1, m1);
	arrr<float> c;
	arrr<float> d;
	arrr<float> z;

	cout << "enter matrix A:\n";
	cin >> a;
	cout << "enter matrix B:\n";
	cin >> b;
	cout << "MIN A: ";
	min(a, n, m);
	cout << "\n";
	cout << "MIN B: ";
	min(b, n1, m1);
	cout << "\n";
	try {
		c = a + b;
		cout << "sum of two matrices A and B :\n" << c;
	}
	catch (arrr<float>::error) {
		cout << "error: the sizes of summable matrices must coincide " << endl;
	}
	try {
		d = a - b;
		cout << "subtraction of two matrices A and B:\n" << d;
	}
	catch (arrr<float>::error)
	{
		cout << "error:the sizes of matrices must coincide" << endl;
	}
	try {
		z = a * b;
		cout << "multiplication of two matrices A and B:\n" << z;
	}
	catch (arrr<float>::error)
	{
		cout << "error: the number of columns of the first matrix must coincide with the number of rows of the second matrix" << endl;
	}
	cout << "All items with paired values are increased three times, matrice A:" << endl;
	parn(a, n, m);
	cout << "All items with paired values are increased three times, matrice B:" << endl;
	parn(b, n1, m1);
}


int main()
{
	int n, m, n1, m1, ch, y = 0;
	cout << "enter number of rows and columns of matrice A: ";
	cin >> m >> n;
	cout << "enter number of rows and columns of matrice B: ";
	cin >> m1 >> n1;

	do {

		cout << "\n 1.INT";
		cout << "\n 2.FLOAT";
		cout << "\n 3.DROBI";
		cout << "\n 4.Exit ";
		cout << "\nEnter Your Choice: ";
		cin >> ch;
		switch (ch)
		{
		case 1:PlayINT(n, m, n1, m1);
			break;
		case 2: PlayFloat(n, m, n1, m1);
			break;
			/*case 3: PlayDROBI(n, m, n1, m1);
			break;*/
		case 4:y = 1;
			break;
		}

	} while (y != 1);

	system("pause");
	return 0;
}

...
Рейтинг: 0 / 0
13.03.2018, 13:27
    #39614080
MasterZiv
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Перегрузка оператора "==" и "="
Iridze,

авторdrobi(int chisl, int zn)
{
chislitel = chisl;
znamenatel = zn;
}
drobi()
{
chislitel = 0;
znamenatel = 0;
}

Используй инициализаторы, а не присваивание в теле конструктора.

Также, если уж ты программист, учись писать названия переменных НА АНГЛИЙСКОМ.
...
Рейтинг: 0 / 0
13.03.2018, 13:30
    #39614081
MasterZiv
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Перегрузка оператора "==" и "="
Iridze,

Код: plaintext
1.
drobi operator+(drobi dr)



Должно быть (не по правилам языка, а по здравой логике)

Код: plaintext
1.
drobi operator+(const drobi &dr) const;




И так по всем операторам.

friend НЕ ИСПОЛЬЗУЙ если это не обязательно.
...
Рейтинг: 0 / 0
13.03.2018, 13:32
    #39614082
MasterZiv
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Перегрузка оператора "==" и "="
Iridze,

Код: plaintext
1.
cout << "The sum of two fractions: ";



Не пиши отладочную печать в теле функций.

Пиши ТЕСТЫ. Печатай ВЕСЬ КЛАСС, а не отдельную переменную.
...
Рейтинг: 0 / 0
13.03.2018, 13:35
    #39614086
MasterZiv
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Перегрузка оператора "==" и "="
IridzeВ общем у меня выдает три ошибки:
бинарный "==": не найден оператор, принимающий левый операнд типа "drobi" (или приемлемое преобразование отсутствует)
бинарный "=": не найден оператор, принимающий правый операнд типа "int" (или приемлемое преобразование отсутствует)
%: недопустимо, левый операнд имеет тип "float"


У тебя ВСЕ операции принимают один из операндов ПО ЗНАЧЕНИЮ.
А конструктора копирования, чтобы твои классы передавать по значению, у тебя НЕТ.

0) конструкторы копирования и (возможно) перемещения надо добавить.
1) оператор присваивания надо добавить.
2) сигнатуры ВСЕХ операций переделать как было указано выше.
3) operator = должен возвращать *this, а не произвольный тип.

Остальное думаю надо смотреть после исправления.
...
Рейтинг: 0 / 0
Форумы / C++ [игнор отключен] [закрыт для гостей] / Перегрузка оператора "==" и "=" / 5 сообщений из 5, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]