I’m trying to write code in C++ (using template) to add between 2 matrices.
I have the following code in .h file.
#ifndef __MATRIX_H__
#define __MATRIX_H__
//***************************
// matrix
//***************************
template <class T, int rows, int cols> class matrix {
public:
T mat[rows][cols];
matrix();
matrix(T _mat[rows][cols]);
matrix operator+(const matrix& b);
};
template <class T, int rows, int cols> matrix <T,rows,cols> :: matrix (T _mat[rows][cols]){
for (int i=0; i<rows; i++){
for (int j=0; j<cols; j++){
mat[i][j] = _mat[i][j];
}
}
}
template <class T, int rows, int cols> matrix <T,rows,cols> :: matrix (){
for (int i=0; i<rows; i++){
for (int j=0; j<cols; j++){
mat[i][j] = 0;
}
}
}
template <class T, int rows, int cols> matrix <T,rows,cols> matrix <T,rows,cols>::operator+(const matrix<T, rows, cols>& b){
matrix<T, rows, cols> tmp;
for (int i=0; i<rows; i++){
for (int j=0; j<cols; j++){
tmp[i][j] = this->mat[i][j] + b.mat[i][j];
}
}
return tmp;
}
#endif
my .cpp :
#include "tar5_matrix.h"
int main(){
int mat1[2][2] = {1,2,3,4};
int mat2[2][2] = {5,6,7,8};
matrix<int, 2, 2> C;
matrix<int, 2, 2> A = mat1;
matrix<int, 2, 2> B = mat2;
C = A+B;
return 0;
}
When compiling, I get the following error:
1>c:userskarindesktopliorstudycppcpp_projectcpp_projecttar5_matrix.h(36):
error C2676: binary ‘[‘ : ‘matrix’ does not define this
operator or a conversion to a type acceptable to the predefined
operator
Please advise
danila-2000 0 / 0 / 0 Регистрация: 15.09.2018 Сообщений: 133 |
||||||||
1 |
||||||||
07.12.2018, 13:42. Показов 2905. Ответов 3 Метки нет (Все метки)
Ошибка C2676 бинарный «—«: «Iterator<T>» не определяет этот оператор или преобразование к типу приемлемо к встроенному оператору
вот сам итератор
0 |
Avaddon74 571 / 353 / 133 Регистрация: 15.09.2017 Сообщений: 1,239 |
||||
07.12.2018, 13:58 |
2 |
|||
danila-2000, ты перегрузил префиксный оператор, а используешь постфиксный Добавлено через 3 минуты
0 |
0 / 0 / 0 Регистрация: 15.09.2018 Сообщений: 133 |
|
07.12.2018, 14:32 [ТС] |
3 |
а если написать —it, то заработает, а будет ли это верно?
0 |
571 / 353 / 133 Регистрация: 15.09.2017 Сообщений: 1,239 |
|
07.12.2018, 15:58 |
4 |
Решение
а будет ли это верно? будет верно.
1 |
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2676 |
Compiler Error C2676 |
06/03/2022 |
C2676 |
C2676 |
838a5e34-c92f-4f65-a597-e150bf8cf737 |
Compiler Error C2676
binary ‘operator‘ : ‘type*’ does not define this operator or a conversion to a type acceptable to the predefined operator
Remarks
To use the operator, you must overload it for the specified type or define a conversion to a type for which the operator is defined.
Examples
The following sample generates C2676.
// C2676.cpp // C2676 expected struct C { C(); } c; struct D { D(); D operator >>( C& ){return * new D;} D operator <<( C& ){return * new D;} } d; struct E { // operator int(); }; int main() { d >> c; d << c; E e1, e2; e1 == e2; // uncomment operator int in class E, then // it is OK even though neither E::operator==(E) nor // operator==(E, E) defined. Uses the conversion to int // and then the builtin-operator==(int, int) }
C2676 can also occur if you attempt to do pointer arithmetic on the this
pointer of a reference type.
The this
pointer is of type handle in a reference type. For more information, see Semantics of the this
pointer.
The following sample generates C2676.
// C2676_a.cpp // compile with: /clr using namespace System; ref struct A { property Double default[Double] { Double get(Double data) { return data*data; } } A() { Console::WriteLine("{0}", this + 3.3); // C2676 Console::WriteLine("{0}", this[3.3]); // OK } }; int main() { A ^ mya = gcnew A(); }
#c #list #struct #compiler-errors
#c #Список #структура #ошибки компилятора
Вопрос:
Я пытаюсь проверить, есть ли уже элемент с таким же значением внутри списка структур, поэтому, если его нет, я возвращаю в список новую структуру.Рассматривайте это как систему с учетными записями, и если учетная запись уже есть, я не хочу снова добавлять ее в список.
Вот мой код в основном:
accounts test;
test.bal = 0;
test.id = 0;
std::list <accounts> accs;
std::list<accounts>::iterator check;
Вот мой код за пределами main:
#include <list>
#include <iterator>
#include <algorithm>
struct accounts {
long id;
int bal;
};
Вот мой код внутри цикла for:
check = find(accs.begin(), accs.end(), test.id);
if (check == accs.end()) {
accs.push_back(test);
}
Когда я запускаю код, я получаю ошибку компилятора :
Ошибка C2676 двоичный файл ‘==’: ‘accounts’ не определяет этот оператор или преобразование в тип, приемлемый для предопределенного оператора bankacc C:Program Файлы (x86)Microsoft Visual Studio2019 Сообщество VCИнструменты MSVC14.28.29333 включить xutility 5440
Я видел другие потоки, и я думаю, что мне нужно сделать
if(check == accs.id.end())
или что-то в этом роде, но это не работает, отображается ошибка:
Ошибка (активная) E0135 класс «std::list<учетные записи, std::распределитель>» не имеет члена «id»
Есть идеи? 🙂
Комментарии:
1. Я думаю, мне нужно сделать как-то не угадать, компилятор показывает вам точную строку.
2. @S.M. позвольте мне улучшить мой вопрос
3.
if(check == accs.id.end())
неверно или является решением.4. Становится очень запутанным читать код, который использует существительные во множественном числе для единственных вещей. Если тип представляет учетную запись, назовите его «учетная запись», а не «учетные записи».
5. @molbdnilo когда я удаляю часть внутри цикла for, код работает, и да, мне жаль, что вы правы насчет имен переменных, я забыл их изменить
Ответ №1:
std::find
принимает объект того же типа, что и типы в вашем контейнере, которые вы хотите найти, в качестве последнего аргумента. В вашем случае вам следует использовать std::find_if
вместо:
check = find_if(accs.begin(), accs.end(),
[amp;test](const autoamp; ac) {
return ac.id == test.id;
});
Комментарии:
1. большое вам спасибо, что сработало. Не могли бы вы объяснить, что на самом деле сделано здесь после [amp;test] ? (На самом деле это сработало, но не подтолкнуло структуру) @johnmastroberti
2. В коде используется лямбда-выражение: https://en.cppreference.com/w/cpp/language/lambda
3. Последний аргумент также
find_if
является функцией, которая должна возвращатьсяtrue
при выполнении условия, которое вы хотите найти. Я добился этого здесь с помощью лямбда (бит от[amp;test]
до конечной фигурной скобки). Подробнее об этом можно прочитать здесь . Код, который я опубликовал, только заменяет ваш вызовfind
. Вам все еще нужны последние три строки, которые у вас были, где вы возвращаете новую учетную запись, если она не была найдена.4. @johnmastroberti ооо, хорошо, большое тебе спасибо. Я полагаю, что обычно для accs размер = 4456540? Потому что я поставил его на просмотр, и это тот размер, который он мне дает
5. Я думаю, вам, вероятно, следует задать отдельный вопрос об этом.
Ответ №2:
Причина довольно проста. Когда вы используете std::find
, под капотом происходит что-то вроде этого,
for(iterator i = begin; i != end; i )
if(*i == check) return i;
Глядя на это, вы можете видеть, что когда мы передаем ваш список, тип итератора — это std::list<accounts>::iterator
то, против чего вы проверяете accounts::id
. Способа сделать это нет.
Итак, какие есть варианты? У вас есть 3,
- Создайте
==
оператор дляaccounts
структуры. - Просто перейдите
test
к тестированию. - Передайте функцию для выполнения сравнения.
Первый простой, вы можете скопировать и вставить это, если хотите,
struct accounts {
long id;
int bal;
bool operator==(const longamp; otherID) const { return id == otherID; }
};
Теперь, когда std::find
вызывается ==
оператор, он знает, что делать.
Третий простой, используйте лямбда-выражение.
check = find(accs.begin(), accs.end(), [amp;test](const accountsamp; other) {
return other.id == test.id; });
if (check == accs.end()) {
accs.push_back(test);
}
Комментарии:
1. Значит, оба списка должны быть итераторами?
2. Извините, я по ошибке опубликовал неправильный ответ (наполовину завершен). Я отредактировал его.
3. Для первой ошибки
Error C2679 binary '==': no operator found which takes a right-hand operand of type 'const _Ty' (or there is no acceptable conversion) bankacc C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.28.29333includexutility 5440
и для 3-й она выдает ту же ошибку, что и раньше4. @TheCodingGuy я ввел
const accountsamp;
там, где это должно бытьconst longamp;
. Извините, я исправил это.5. Спасибо, что исправлена ошибка, но по какой-то причине структура не нажимается и получает числа, которые она не должна, вероятно, это моя ошибка где-то спасибо, хотя
Ответ №3:
Просто перегрузите оператор «==». В параметрах выберите желаемый тип значения, которое вы хотите.
hi!!
i just started programming some stuff in c++.
i made a simple program that compares a number given by the user to 0 n say if its cero, positive or negative.
// num_positivo_negativo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <math.h>
#include <windows.h>
#include <stdio.h>
#include <iostream> //para las versiones nuevas de C++
#include <iostream.h> //para las versiones más viejas, como Borland C++
int main(int argc,char* argv[])
{
int num;
cout << " Ingrese un número: ";
cin << num;
if (num = 0)
{
cout << "El número es igual a cero"; // says that is 0
}
else
if (num < 0)
{
cout <<"Numero negativo"; // says that is negative
}
else
{
cout <<"Numero positivo"; // says that is positive
}
return 0;
}
but, then it gave me this error:
num_positivo_negativo.cpp(17) : error C2676: binary ‘<<‘ : ‘class istream_withassign’ does not define this operator or a conversion to a type acceptable to the predefined operator
hope some1 can help me
thanks!!
cyaa!!
gispe!!