Задание
Создать класс — комплексные числа. Определить необходимые конструкторы и деструктор. Перегрузить поточные операции ввода и вывода, операции +, -, *, / и ^. Вычислить значение выражения у = а * х2 + b * х + с для комплексных коэффициентов a, b, c в комплексной точке х.
Код
#include <iostream>
#include <assert.h>
using namespace std;
class complex
{
double re, im;
public:
complex(double=0,double=0);
~complex();
complex operator +(complex&);
complex operator -(complex&);
complex operator *(complex&);
complex operator /(complex&);
complex operator ^(unsigned);
friend istream& operator >>(istream&,complex&);
friend ostream& operator <<(ostream&,complex&);
};
complex::complex(double r, double i)
{
re=r; im=i;
}
complex::~complex()
{
}
complex complex::operator +(complex& y)
{
return complex(re+y.re, im+y.im);
}
complex complex::operator -(complex& y)
{
return complex(re-y.re, im-y.im);
}
complex complex::operator *(complex& y)
{
return complex(re*y.re-im*y.im, re*y.im+im*y.re);
}
complex complex::operator /(complex& y)
{
double r1=re;
double i1=im;
double r2=y.re;
double i2=y.im;
return complex((r1*r2-i1*i2)/(r2*r2+i2*i2),(-r1*i2+i1*r2)
/(r2*r2+i2*i2));
}
complex complex:: operator^(unsigned n)
{
complex y(1,0);
for(unsigned i=1;i<=n;i++)
y=y*(*this);
return y;
}
istream& operator >>(istream& is, complex& x)
{
char c;
is>>x.re;
cin>>c;
assert(c==',');
is>>x.im;
return is;
}
ostream& operator <<(ostream& os, complex& x)
{
os<<x.re<<','<<x.im<<endl;
return os;
}
int main()
{
complex a(1,1), b(1,1), c(1,1);
complex x;
cout<<"Введите комплексное число в формате: re,im ";
cin>>x;
cout<<"Результат = "<<a * (x ^ 2) + b * x + c <<endl;
return 0;
}
Ошибки
cout<<"Результат = "<<a * (x ^ 2) + b * x + c <<endl;
Ошибка (активно) E0349 отсутствует оператор «*», соответствующий этим операндам
Ошибка C2679 бинарный «*»: не найден оператор, принимающий правый операнд типа «complex» (или приемлемое преобразование отсутствует)
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 |
#include <iostream> #include <Windows.h> #include <string> using namespace std; #define DLL_LOAD_ERR -1 int (*lenght)(char* s); int (*Sravnenie) (char s1[], char s2[]); void (*unity)(char* s1, char* s2); void (*del)(char* s, int st, int leng, char* fin); void (*Copy)(char* s, int st, int leng, char* fin); int (*search)(char* s1, char* s2); int (*strsearch)(char* s1, char* s2); int (*lenfin)(char* s); HMODULE LibInst; int OpenDLL() { LibInst = LoadLibraryA("C:\VS2017\C++\Library\DLL_Library\STRLibrary"); if (LibInst) { lenght = (int(*)(char * s)) GetProcAddress(LibInst, "lenght"); Sravnenie = (int(*)(char s1[], char s2[])) GetProcAddress(LibInst, "Sravnenie"); unity = (void(*)(char* s1, char* s2)) GetProcAddress(LibInst, "unity"); del = (void(*)(char* s, int st, int leng, char* fin)) GetProcAddress(LibInst, "del"); Copy = (void(*)(char* s, int st, int leng, char* fin)) GetProcAddress(LibInst, "Copy"); return 0; }; return DLL_LOAD_ERR; } void CloseDLL() { FreeLibrary(LibInst); } int main() { std::cout << "Hello World!n"; if (OpenDLL() == 0) { SetConsoleCP(1251); SetConsoleOutputCP(1251); int st, len; char finstr[100]; char s1[100]; char s2[100]; char s3[100]; char s4[100]; cout << "Введите строку 1: "; cin.getline(s1, 50); cout << "Введите строку 2: "; cin.getline(s2, 50); cout << "Длина первой строки:" << endl; cout << lenght(s1) << endl; cout << "Сравнение строк:" << endl; cout << Sravnenie(s1, s2) << endl; cout << "Соединение строк:" << endl; cout << unity(s1, s2) << endl; //отсутствует оператор "<<", соответствующий этим операндам cout << "введите позицию удаляемой части:" << endl; cin >> st; cout << "Введите длину удаляемой части:" << endl; cin >> len; cout << "Результат удаления:" << endl; cout << del(s1, st, len, finstr) << endl; //отсутствует оператор "<<", соответствующий этим операндам cout << "введите позицию копирования:" << endl; cin >> st; cout << "Введите длину копирования части:" << endl; cin >> len; cout << "Результат копирования:" << endl; cout << Copy(s1, st, len, finstr) << endl; //Ошибка (активно) E0349 отсутствует оператор "<<", соответствующий этим операндам |
I have date installed using vcpkg.
#include <iostream>
#include "date/date.h"
int main()
{
auto today = floor<date::days>(std::chrono::system_clock::now());
std::cout << today << 'n';
std::cout << "Hello World!n";
}
building above code rise the error
E0349 no operator «<<» matches these operands
VS 2019 : version 16.7.0
Standard : ISO C++17 Standard (std:c++17)
Platform Toolset : Visual Studio 2019 (v142)
Unfortunately the streaming operators are in namespace date
instead of namespace std::chrono
. And the type of today
is a std::chrono::time_point
type. This means that you’ll need to manually expose the streaming operators because ADL won’t find them.
The most precise way to do this is:
This also works, and often is already done for other reasons:
When we get this lib in C++20, the streaming operators will be found by ADL in namespace std::chrono
and this step will no longer be necessary.
another problem with this library is that when i place windows.h include directive on top of date/date so many errors arise.
but when i place windows.h include directive below of data/date.h no error arised.
**#include <windows.h>**
#include <iostream>
#include <chrono>
#include "date/tz.h"
#include "date/date.h"
using namespace date;
using namespace std::chrono;
// to move back to the beginning and output again
void gotoxy(int x, int y)
{
COORD coord; // coordinates
coord.X = x; coord.Y = y; // X and Y coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); // moves to the coordinates
}
int main()
{
while (true)
{
gotoxy(0, 0);
std::cout << date::zoned_time{ date::current_zone(), std::chrono::system_clock::now() }.get_local_time() << 'n';
}
std::getchar();
}
Severity Code Description Project File Line Suppression State
Error (active) E0070 incomplete type is not allowed DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error (active) E0040 expected an identifier DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: '(' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2143 syntax error: missing ',' before '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2535 'date::year::year(void)': member function already defined or declared DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: 'noexcept' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2334 unexpected token(s) preceding '{'; skipping apparent function body DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: '(' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2143 syntax error: missing ',' before '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2535 'date::year::year(void)': member function already defined or declared DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2059 syntax error: '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2059 syntax error: 'noexcept' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2334 unexpected token(s) preceding '{'; skipping apparent function body DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1169
Error C2059 syntax error: '(' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1169
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1630
Error C2062 type 'unknown-type' unexpected DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1630
Error C2059 syntax error: ')' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1630
Error C3615 constexpr function 'date::year::ok' cannot result in a constant expression DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1628
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 6106
Error C2760 syntax error: unexpected token '(', expected ')' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 6106
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 6327
Define NOMINMAX
to disable the Windows min
and max
macros.
Adding #include helps for this problem when a string used by cout or cin
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <cstring>
#include <list>
using namespace std;
int main()
{
char message[] = "Привет мир";
char alphabet[] = { '&', 'а', 'м', 'Й', 'ю', '4', 'p', '=', 'F', '7', 'Ц', 'H', 'a', 'O', 'Ш', 'R', 'Л', 'M', 'з', 'I', 'о', '!', 'Н', '2', 'j', '5', 'Ж', '6', '0', 'Ю', 'ч', 'C', 'm', 'З', 'в', '+', '1', 'u', 'G', 'Z', '#', 'т', 'c', '.', 'э', 'e', '3', 'х', 'у', 'Y', 'd', 'D', 'Д', '%', 'й', 'r', 'Q', 'д', 'щ', 'N', '-', 'V', 'y', 'С', 'Ч', 'Б', '8', 'К', 'X', 'T', '9', 'b', 'S', '$', 'М', 'A', 'L', 'q', 'Р', '@', 'р', 'У', 'ё', 'E', 'Ф', '~', 'л', 'О', 'и', 'Х', 't', 'ж', 'k', 'w', 'f', 'Э', 'е', 'П', 'B', 'И', 'Ё', '?', ',', 'ц', 'v', 'ш', 'б', 's', 'н', 'l', 'g', 'А', 'Т', 'я', 'n', 'J', 'K', 'h', 'В', 'x', 'i', 'с', 'U', 'W', 'п', 'к', 'P', 'ф', 'Е', 'z', 'o', 'г' };
int key = 1;// GetRandomNumber(0, 16);
list<char> result;
for (int index = 0; index < strlen(message); index++)
{
char elem = message[index];
if (index + key > size(alphabet) + 1)
{
index = index + key - size(alphabet);
}
else
{
index = index + key;
}
result.push_back(alphabet[index]);
}
cout << result;
}
Ошибка (активно) E0349 отсутствует оператор «<<«, соответствующий этим операндам 31 строка
Как пофиксить эту ошибку и вывести список?
Перейти к контенту
MaxMart 0 / 0 / 0 Регистрация: 29.07.2019 Сообщений: 10 |
||||
1 |
||||
29.07.2019, 15:12. Показов 11004. Ответов 4 Метки нет (Все метки)
Всем привет! Начал изучать С++ по книжке Герберта Шилдта. Дошёл до перегрузки оператора присвоения и столкнулся с такой ошибкой. И до этого были небольшие ошибки, всё же что-то новое появляется, что-то изменяется. Вообщем помогите пожалуйста разобраться в чём проблема!!!
__________________ 0 |
шКодер самоучка 2173 / 1880 / 912 Регистрация: 09.10.2013 Сообщений: 4,135 Записей в блоге: 7 |
|
29.07.2019, 15:24 |
2 |
MaxMart, у вас неправильная сигнатура для operator=: 1 |
MaxMart 0 / 0 / 0 Регистрация: 29.07.2019 Сообщений: 10 |
||||
29.07.2019, 19:35 [ТС] |
3 |
|||
Я писал с книги, возможно в ней опечатка, замечал такое в предыдущих упражнениях. В моём случае как будет верно? Добавлено через 18 минут
Только осталась еще одна не решёная проблема, а именно: Ошибка C4996 ‘strcpy’: This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 0 |
817 / 504 / 211 Регистрация: 19.01.2019 Сообщений: 1,196 |
|
29.07.2019, 20:04 |
4 |
_CRT_SECURE_NO_WARNINGS #pragma warning(disable:4996) 0 |
0 / 0 / 0 Регистрация: 29.07.2019 Сообщений: 10 |
|
29.07.2019, 22:31 [ТС] |
5 |
Max Dark, спасибо, я разобрался!!!) 0 |
Пишу программу на С++, в которой надо разработать определения двух классов COne и CTwo, которые связаны отношением включения. Проблема возникает в мейне, при попытке вывести A.getObj()
.
Сама ошибка : 0349 отсутствует оператор «<<«, соответствующий этим операндам
Скорее всего ошибка возникает из-за того, что в классе отсутствует нужный метод. Помогите с его реализацией, пожалуйста
//MAIN
#include <iostream>
#include <String.h>
#include "CTwo.h"
#include "COne.h"
using namespace std;
int main()
{
CTwo A("CTwo String","COne String", 505);
A.Print();
cout << A.getS() << endl;
cout << A.getObj() << endl; // <==== ошибка тут
}
//COne.h
#ifndef CONE_H
#define CONE_H
#include <iostream>
#include <string>
using namespace std;
class COne
{
protected:
string s;
double d;
public:
COne();
COne(string S, double D);
~COne();
COne(const COne& arg);
void print();
COne(COne& arg);
const double& getD();
const string& getS();
void Print();
COne& operator=(const COne& arg);
friend class CTwo;
};
#endif
//CTwo.h
#ifndef CTWO_H
#define CTWO_H
#include <iostream>
#include <string>
#include "COne.h"
using namespace std;
class COne;
class CTwo
{
protected:
string s;
COne obj;
public:
CTwo();
CTwo(string S, string SOne, double d);
virtual ~CTwo();
void Print();
const string& getS();
const COne& getObj();
friend class COne;
};
#endif
The problem is that you are trying to use an iterator-based range-for
loop with a dynamic array. hashtable
is a pointer to a list[]
array, and a range-for
loop simply can’t get the iterators it needs from a raw pointer to an array.
You will have to use a non-range for
loop to iterate the array, eg:
void printHashTable()
{
for(int i = 0; i < tableSize; ++i)
{
for (auto &x : hashtable[i])
{
cout << "--->" << x;
}
cout << endl;
}
cout << endl;
}
Otherwise, use a std::vector
instead of new[]
(especially since you are leaking the hashTable
anyway), then you can use a range-for
loop to iterate the array, eg:
#include <iostream>
#include <list>
#include <string>
#include <vector>
using namespace std;
class Student
{
string name;
int age;
double fee;
};
class Hash
{
private:
vector<list<Student>> hashTable;
public:
Hash(int size)
: hashTable(size)
{
}
int hashFunction(int key)
{
return (key % hashTable.size());
}
void insertItem(int key, Student value)
{
int index = hashFunction(key);
hashTable[index].push_back(value);
}
void printHashTable()
{
for (auto &l : hashtable)
{
for (auto &x : l)
{
cout << "--->" << x;
}
cout << endl;
}
cout << endl;
}
};
The problem is that you are trying to use an iterator-based range-for
loop with a dynamic array. hashtable
is a pointer to a list[]
array, and a range-for
loop simply can’t get the iterators it needs from a raw pointer to an array.
You will have to use a non-range for
loop to iterate the array, eg:
void printHashTable()
{
for(int i = 0; i < tableSize; ++i)
{
for (auto &x : hashtable[i])
{
cout << "--->" << x;
}
cout << endl;
}
cout << endl;
}
Otherwise, use a std::vector
instead of new[]
(especially since you are leaking the hashTable
anyway), then you can use a range-for
loop to iterate the array, eg:
#include <iostream>
#include <list>
#include <string>
#include <vector>
using namespace std;
class Student
{
string name;
int age;
double fee;
};
class Hash
{
private:
vector<list<Student>> hashTable;
public:
Hash(int size)
: hashTable(size)
{
}
int hashFunction(int key)
{
return (key % hashTable.size());
}
void insertItem(int key, Student value)
{
int index = hashFunction(key);
hashTable[index].push_back(value);
}
void printHashTable()
{
for (auto &l : hashtable)
{
for (auto &x : l)
{
cout << "--->" << x;
}
cout << endl;
}
cout << endl;
}
};
I have date installed using vcpkg.
#include <iostream>
#include "date/date.h"
int main()
{
auto today = floor<date::days>(std::chrono::system_clock::now());
std::cout << today << 'n';
std::cout << "Hello World!n";
}
building above code rise the error
E0349 no operator «<<» matches these operands
VS 2019 : version 16.7.0
Standard : ISO C++17 Standard (std:c++17)
Platform Toolset : Visual Studio 2019 (v142)
Unfortunately the streaming operators are in namespace date
instead of namespace std::chrono
. And the type of today
is a std::chrono::time_point
type. This means that you’ll need to manually expose the streaming operators because ADL won’t find them.
The most precise way to do this is:
This also works, and often is already done for other reasons:
When we get this lib in C++20, the streaming operators will be found by ADL in namespace std::chrono
and this step will no longer be necessary.
another problem with this library is that when i place windows.h include directive on top of date/date so many errors arise.
but when i place windows.h include directive below of data/date.h no error arised.
**#include <windows.h>**
#include <iostream>
#include <chrono>
#include "date/tz.h"
#include "date/date.h"
using namespace date;
using namespace std::chrono;
// to move back to the beginning and output again
void gotoxy(int x, int y)
{
COORD coord; // coordinates
coord.X = x; coord.Y = y; // X and Y coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); // moves to the coordinates
}
int main()
{
while (true)
{
gotoxy(0, 0);
std::cout << date::zoned_time{ date::current_zone(), std::chrono::system_clock::now() }.get_local_time() << 'n';
}
std::getchar();
}
Severity Code Description Project File Line Suppression State
Error (active) E0070 incomplete type is not allowed DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error (active) E0040 expected an identifier DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: '(' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2143 syntax error: missing ',' before '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2535 'date::year::year(void)': member function already defined or declared DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: 'noexcept' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2334 unexpected token(s) preceding '{'; skipping apparent function body DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: '(' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2143 syntax error: missing ',' before '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2535 'date::year::year(void)': member function already defined or declared DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2059 syntax error: '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2059 syntax error: 'noexcept' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2334 unexpected token(s) preceding '{'; skipping apparent function body DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1169
Error C2059 syntax error: '(' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1169
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1630
Error C2062 type 'unknown-type' unexpected DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1630
Error C2059 syntax error: ')' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1630
Error C3615 constexpr function 'date::year::ok' cannot result in a constant expression DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1628
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 6106
Error C2760 syntax error: unexpected token '(', expected ')' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 6106
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 6327
Define NOMINMAX
to disable the Windows min
and max
macros.
Adding #include helps for this problem when a string used by cout or cin
- Forum
- Beginners
- Unexpected E0349 error
Unexpected E0349 error
I have two instances of the following code just built in two different projects on the same visual studio package on the same machine at approximately the same time. On the first project the code compiled and ran with no problems.
I created a new project and entered the code but the second attempt failed giving E0349 errors ‘no operator «>>» and «<<» matchs these operands along with a number of other errors.
I can find no references to this behavior on the internet or any of my manuals.
I have retyped the errant code numerous times with the same results.
I have Copied and pasted the code into the second window, still fails.
I created a third project and pasted the code. Still fails
I suspect I am making at least one stupid mistake but I cannot find it.
Any help you could give would be greatly appreciated.
Both instances of the code look identical to me down to the line counts.
I have a screen shot of both windows side by side if that would help.
.
|
|
Try adding #include <string> and moving «using namespace std» to just after the includes.
And remember, when dealing with a bunch of errors, deal with the very first one first (scroll back if necessary to find it). Other errors may just be a cascade of problems due to the first.
Last edited on
Topic archived. No new replies allowed.
Не удается скомпилировать мой код — я получаю: оператор «<<» не соответствует этим операндам
Я нашел аналогичную проблему. Оператор «<<» не соответствует этим операндам, однако у меня нет строк или отсутствующих директив (я думаю)
Может ли кто-нибудь помочь мне, пожалуйста?
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <iomanip>
#include <vector>void convBase(int base, int n);
using std::cout;
using std::endl;
using std::setw;
using std::vector;int main()
{int numbs[] = { 61, 0, -9, -200, 9999 };
int bases[] = { 16, 8, 2, 20, 36 };
size_t size = sizeof(numbs) / sizeof(*numbs);for (size_t i = 0; i < size; ++i) {
cout << setw(4) << numbs[i] << " = " << setw(5)
<< convBase(numbs[i], bases[i]) << " in base "
<< setw(2) << bases[i] << endl;
}
return 0;}
void convBase(int n, int base) {
char pierwszyZnak = 48;
char pierwszaLitera = 65;
vector<char> system;
vector<char> liczba;for (int i = 0; i < base; i++) {
if (i <= 9) {
system.push_back(pierwszyZnak);
pierwszyZnak++;
}
else if (i <= 36) {
system.push_back(pierwszaLitera);
pierwszaLitera++;
}
else {
cout << "podales za duza liczbe: " << base << ". Musisz podac liczbe mniejsza badz rowna 36" << endl;
return;
}
}while (n > 0) {
int rem = n % base;
int rem2 = floor(n / base);
liczba.push_back(system[rem]);
n = rem2;
}
for (unsigned int i = liczba.size(); i-- > 0; )
std::cout << liczba[i];
}
E0349: ни один оператор «=» не соответствует этим операндам при использовании JSON с использованием nlohmann-json.
Я использую nlohmann-json в своем проекте C++ в Visual Studio, и я обнаружил ошибку
E0349:no operator " = " matches these operands
В коде ниже:
#include <nlohmann/json.hpp>
using json = nlohmann::json;
void myFunc(unsigned int** arr) {
json j;
j["myArr"] = arr;//E0349:no operator " = " matches these operands
}
Что не так ?
С другой стороны, когда я пробую следующий, он работает.
void myFunc(unsigned int** arr) {
json j;
j["myArr"] = {1,2,3};// no error
}
Я предполагаю, что это связано с проблемой типа данных.
Буду признателен за любую информацию.
ten, 31 марта 2021 г., 08:32
1
48
1
Ответ:
Решено
Nlohmann json поддерживает создание массивов только из контейнеров стандартной библиотеки С ++. Невозможно создать массив из указателя, поскольку он не имеет информации о размере массива.
Если у вас есть C++ 20, вы можете использовать std::span для преобразования указателя (и размера) в контейнер:
#include <nlohmann/json.hpp>
#include <span>
using json = nlohmann::json;
void myFunc(unsigned int* arr, size_t size) {
json j;
j["myArr"] = std::span(arr, size);
}
Если у вас нет C++ 20, вам придется либо реализовать std::span самостоятельно, либо скопировать свой массив во что-то вроде std::vector (или просто использовать std::vector для начала, а не необработанные массивы).
В качестве альтернативы создайте массив вручную (здесь вам все равно нужен размер):
void myFunc(unsigned int* arr, size_t size) {
json j;
auto& myArr = j["myArr"];
for (size_t i = 0; i < size; i++)
{
myArr.push_back(arr[i]);
}
}
Alan, 31 марта 2021 г., 10:22
Интересные вопросы для изучения
Я пробовал с и без #include <iostream>
#include <string>
или даже using namespace std
и ничего не изменилось. Параметры должны быть ссылками. При попытке запустить код я получаю следующую ошибку: E0349 no operator ">>" matches these operands
в строке 9.
#include <iostream>
#include <string>
#include "Person.h"#include <cstdio>
using namespace std;
//Extending istream to support the Person class
std::istream & operator>>(std::istream & is, Person & p) {
is >> p.getName() >> p.getAge();
return is;
}
//Extending ostream to support the Person class
std::ostream & operator<<(std::ostream & os, Person & p) {
os << "[" << p.getName()<<"," << p.getAge()<<"]";
}
int main() {
Person *pOne = new Person();
cout << "Person1's name is: " << pOne->getName() << endl;
cin >> *pOne;
getchar(); //Just to leave the console window open
return 0;
}
Код от Person.h:
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
string name;
short age;
public:
Person();
virtual ~Person();
Person(string, short);
string getName();
short getAge();
};
А вот код из Person.cpp:
#include "Person.h"#include <iostream>
#include <string>
using namespace std;
Person::Person()
:name("[Unassigned Name]"), age(0)
{
cout << "Hello from Person::Person" << endl;
}
Person::~Person()
{
cout << "Goodbye from Person::~Person" << endl;
}
Person::Person(string name, short age)
:name(name), age(age)
{
cout << "Hello from Person::Person" << endl;
}
string Person::getName()
{
return this->name;
}
short Person::getAge()
{
return this->age;
}
Первый >>
в строке 9 сразу после is
подчеркнуто красным. Я пользуюсь Visual Studio 2017 Community.
-1
Решение
Проблема в том, что оператору >> нужно что-то, что он может изменять. Возвращаемое значение функции типа getName
это не такая вещь.
Вот как вы обычно делаете это, чтобы сделать оператор >> дружественной функцией, чтобы он мог напрямую обращаться к внутренним объектам Person
учебный класс.
class Person
{
// make operator>> a friend function
friend std::istream & operator>>(std::istream & is, Person & p);
private:
string name;
short age;
public:
Person(string, short);
string getName();
short getAge();
};
//Extending istream to support the Person class
std::istream & operator>>(std::istream & is, Person & p) {
is >> p.name >> p.age;
return is;
}
Не единственный способ, хотя. Вот еще один подход, который не должен заставлять кого-либо функционировать. Он использует временные переменные, а затем создает и назначает объект Person из этих временных переменных.
//Extending istream to support the Person class
std::istream & operator>>(std::istream & is, Person & p) {
string name;
short age;
is >> name >> age;
p = Person(name, age);
return is;
}
1
Другие решения
Других решений пока нет …
You are trying to pass the return value of snakeorladder()
to cout << ...
, but snakeorladder()
has a void
return value — ie, it doesn’t return anything at all. So there is nothing to pass to operator<<
.
Simply get rid of the print statement in main()
, especially since snakeorladder()
already prints everything internally:
int main()
{
snakeorladder(place25);
}
Otherwise, you would have to change snakeorladder()
to return something that main()
can actually print, eg:
const char* snakeorladder(int myplace)
{
char L1Top = 0, L1Bot = 0, L2Top = 0, L2Bot = 0, L3Top = 0, L3Bot = 0, S1Top = 0, S1Bot = 0, S2Top = 0, S2Bot = 0, S3Top = 0, S3Bot = 0;
if (L1Top == myplace)
return "L1Top";
if (L1Bot == myplace)
return "L1Bot";
if (L2Top == myplace)
return "L2Top";
if (L2Bot == myplace)
return "L2Bot";
if (L3Top == myplace)
return "L3Top";
if (L3Bot == myplace)
return "L3Bot";
if (S1Top == myplace)
return "S1Top";
if (S1Bot == myplace)
return "S1Bot";
if (S2Top == myplace)
return "S2Top";
if (S2Bot == myplace)
return "S2Bot";
if (S3Top == myplace)
return "S3Top";
if (S3Bot == myplace)
return "S3Bot";
return "";
};
int main()
{
cout << snakeorladder(place25);
}
Перейти к контенту
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 |
#include <iostream> #include <Windows.h> #include <string> using namespace std; #define DLL_LOAD_ERR -1 int (*lenght)(char* s); int (*Sravnenie) (char s1[], char s2[]); void (*unity)(char* s1, char* s2); void (*del)(char* s, int st, int leng, char* fin); void (*Copy)(char* s, int st, int leng, char* fin); int (*search)(char* s1, char* s2); int (*strsearch)(char* s1, char* s2); int (*lenfin)(char* s); HMODULE LibInst; int OpenDLL() { LibInst = LoadLibraryA("C:VS2017C++LibraryDLL_LibrarySTRLibrary"); if (LibInst) { lenght = (int(*)(char * s)) GetProcAddress(LibInst, "lenght"); Sravnenie = (int(*)(char s1[], char s2[])) GetProcAddress(LibInst, "Sravnenie"); unity = (void(*)(char* s1, char* s2)) GetProcAddress(LibInst, "unity"); del = (void(*)(char* s, int st, int leng, char* fin)) GetProcAddress(LibInst, "del"); Copy = (void(*)(char* s, int st, int leng, char* fin)) GetProcAddress(LibInst, "Copy"); return 0; }; return DLL_LOAD_ERR; } void CloseDLL() { FreeLibrary(LibInst); } int main() { std::cout << "Hello World!n"; if (OpenDLL() == 0) { SetConsoleCP(1251); SetConsoleOutputCP(1251); int st, len; char finstr[100]; char s1[100]; char s2[100]; char s3[100]; char s4[100]; cout << "Введите строку 1: "; cin.getline(s1, 50); cout << "Введите строку 2: "; cin.getline(s2, 50); cout << "Длина первой строки:" << endl; cout << lenght(s1) << endl; cout << "Сравнение строк:" << endl; cout << Sravnenie(s1, s2) << endl; cout << "Соединение строк:" << endl; cout << unity(s1, s2) << endl; //отсутствует оператор "<<", соответствующий этим операндам cout << "введите позицию удаляемой части:" << endl; cin >> st; cout << "Введите длину удаляемой части:" << endl; cin >> len; cout << "Результат удаления:" << endl; cout << del(s1, st, len, finstr) << endl; //отсутствует оператор "<<", соответствующий этим операндам cout << "введите позицию копирования:" << endl; cin >> st; cout << "Введите длину копирования части:" << endl; cin >> len; cout << "Результат копирования:" << endl; cout << Copy(s1, st, len, finstr) << endl; //Ошибка (активно) E0349 отсутствует оператор "<<", соответствующий этим операндам |
Пишу программу на С++, в которой надо разработать определения двух классов COne и CTwo, которые связаны отношением включения. Проблема возникает в мейне, при попытке вывести A.getObj()
.
Сама ошибка : 0349 отсутствует оператор «<<«, соответствующий этим операндам
Скорее всего ошибка возникает из-за того, что в классе отсутствует нужный метод. Помогите с его реализацией, пожалуйста
//MAIN
#include <iostream>
#include <String.h>
#include "CTwo.h"
#include "COne.h"
using namespace std;
int main()
{
CTwo A("CTwo String","COne String", 505);
A.Print();
cout << A.getS() << endl;
cout << A.getObj() << endl; // <==== ошибка тут
}
//COne.h
#ifndef CONE_H
#define CONE_H
#include <iostream>
#include <string>
using namespace std;
class COne
{
protected:
string s;
double d;
public:
COne();
COne(string S, double D);
~COne();
COne(const COne& arg);
void print();
COne(COne& arg);
const double& getD();
const string& getS();
void Print();
COne& operator=(const COne& arg);
friend class CTwo;
};
#endif
//CTwo.h
#ifndef CTWO_H
#define CTWO_H
#include <iostream>
#include <string>
#include "COne.h"
using namespace std;
class COne;
class CTwo
{
protected:
string s;
COne obj;
public:
CTwo();
CTwo(string S, string SOne, double d);
virtual ~CTwo();
void Print();
const string& getS();
const COne& getObj();
friend class COne;
};
#endif
I have date installed using vcpkg.
#include <iostream>
#include "date/date.h"
int main()
{
auto today = floor<date::days>(std::chrono::system_clock::now());
std::cout << today << 'n';
std::cout << "Hello World!n";
}
building above code rise the error
E0349 no operator «<<» matches these operands
VS 2019 : version 16.7.0
Standard : ISO C++17 Standard (std:c++17)
Platform Toolset : Visual Studio 2019 (v142)
Unfortunately the streaming operators are in namespace date
instead of namespace std::chrono
. And the type of today
is a std::chrono::time_point
type. This means that you’ll need to manually expose the streaming operators because ADL won’t find them.
The most precise way to do this is:
This also works, and often is already done for other reasons:
When we get this lib in C++20, the streaming operators will be found by ADL in namespace std::chrono
and this step will no longer be necessary.
another problem with this library is that when i place windows.h include directive on top of date/date so many errors arise.
but when i place windows.h include directive below of data/date.h no error arised.
**#include <windows.h>**
#include <iostream>
#include <chrono>
#include "date/tz.h"
#include "date/date.h"
using namespace date;
using namespace std::chrono;
// to move back to the beginning and output again
void gotoxy(int x, int y)
{
COORD coord; // coordinates
coord.X = x; coord.Y = y; // X and Y coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); // moves to the coordinates
}
int main()
{
while (true)
{
gotoxy(0, 0);
std::cout << date::zoned_time{ date::current_zone(), std::chrono::system_clock::now() }.get_local_time() << 'n';
}
std::getchar();
}
Severity Code Description Project File Line Suppression State
Error (active) E0070 incomplete type is not allowed DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error (active) E0040 expected an identifier DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: '(' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2143 syntax error: missing ',' before '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2535 'date::year::year(void)': member function already defined or declared DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: 'noexcept' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2334 unexpected token(s) preceding '{'; skipping apparent function body DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 421
Error C2059 syntax error: '(' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2143 syntax error: missing ',' before '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2535 'date::year::year(void)': member function already defined or declared DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2059 syntax error: '?' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2059 syntax error: 'noexcept' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2334 unexpected token(s) preceding '{'; skipping apparent function body DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 422
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1169
Error C2059 syntax error: '(' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1169
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1630
Error C2062 type 'unknown-type' unexpected DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1630
Error C2059 syntax error: ')' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1630
Error C3615 constexpr function 'date::year::ok' cannot result in a constant expression DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 1628
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 6106
Error C2760 syntax error: unexpected token '(', expected ')' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 6106
Error C2589 '(': illegal token on right side of '::' DateTimeSamples C:Devvcpkginstalledx64-windowsincludedatedate.h 6327
Define NOMINMAX
to disable the Windows min
and max
macros.
Adding #include helps for this problem when a string used by cout or cin
You are trying to pass the return value of snakeorladder()
to cout << ...
, but snakeorladder()
has a void
return value — ie, it doesn’t return anything at all. So there is nothing to pass to operator<<
.
Simply get rid of the print statement in main()
, especially since snakeorladder()
already prints everything internally:
int main()
{
snakeorladder(place25);
}
Otherwise, you would have to change snakeorladder()
to return something that main()
can actually print, eg:
const char* snakeorladder(int myplace)
{
char L1Top = 0, L1Bot = 0, L2Top = 0, L2Bot = 0, L3Top = 0, L3Bot = 0, S1Top = 0, S1Bot = 0, S2Top = 0, S2Bot = 0, S3Top = 0, S3Bot = 0;
if (L1Top == myplace)
return "L1Top";
if (L1Bot == myplace)
return "L1Bot";
if (L2Top == myplace)
return "L2Top";
if (L2Bot == myplace)
return "L2Bot";
if (L3Top == myplace)
return "L3Top";
if (L3Bot == myplace)
return "L3Bot";
if (S1Top == myplace)
return "S1Top";
if (S1Bot == myplace)
return "S1Bot";
if (S2Top == myplace)
return "S2Top";
if (S2Bot == myplace)
return "S2Bot";
if (S3Top == myplace)
return "S3Top";
if (S3Bot == myplace)
return "S3Bot";
return "";
};
int main()
{
cout << snakeorladder(place25);
}
You are trying to pass the return value of snakeorladder()
to cout << ...
, but snakeorladder()
has a void
return value — ie, it doesn’t return anything at all. So there is nothing to pass to operator<<
.
Simply get rid of the print statement in main()
, especially since snakeorladder()
already prints everything internally:
int main()
{
snakeorladder(place25);
}
Otherwise, you would have to change snakeorladder()
to return something that main()
can actually print, eg:
const char* snakeorladder(int myplace)
{
char L1Top = 0, L1Bot = 0, L2Top = 0, L2Bot = 0, L3Top = 0, L3Bot = 0, S1Top = 0, S1Bot = 0, S2Top = 0, S2Bot = 0, S3Top = 0, S3Bot = 0;
if (L1Top == myplace)
return "L1Top";
if (L1Bot == myplace)
return "L1Bot";
if (L2Top == myplace)
return "L2Top";
if (L2Bot == myplace)
return "L2Bot";
if (L3Top == myplace)
return "L3Top";
if (L3Bot == myplace)
return "L3Bot";
if (S1Top == myplace)
return "S1Top";
if (S1Bot == myplace)
return "S1Bot";
if (S2Top == myplace)
return "S2Top";
if (S2Bot == myplace)
return "S2Bot";
if (S3Top == myplace)
return "S3Top";
if (S3Bot == myplace)
return "S3Bot";
return "";
};
int main()
{
cout << snakeorladder(place25);
}
The debugger encounters this error and it is hereby logged.
#include<iostream>
using namespace std;
class Point {
private:
int _x, _y;
public:
Point(int x=0,int y=0):_x(x),_y(y){}
Point& operator++();
Point operator++(int);
Point& operator--();
Point operator--(int);
friend ostream& operator<<(ostream& ostr,const Point& p);
};
Point& Point::operator++()
{
_x++;
_y++;
return *this;
}
Point Point::operator++(int)
{
Point temp = *this;
++* this;//Reuse the overload of prefix ++
return temp;
}
Point& Point::operator--()
{
_x--;
_y--;
return *this;
}
Point Point::operator--(int)
{
Point temp = *this;
--* this;
return temp;
}
ostream& operator<<(ostream& ostr,Point& p)
{
ostr << '(' << p._x << "," << p._y << ')';
return ostr;
}
int main()
{
Point p(1, 2);
cout << p << endl;
cout << p++ << endl;
cout << ++p << endl;
cout << p-- << endl;
cout << --p << endl;
return 0;
}
Then in the main function
cout << p++ << endl;
cout << p-- << endl;
These two places reported this error.
After searching online, I learned:
p++ returns a temporary object. The temporary object is a pure rvalue. It cannot be bound to an lvalue reference. It needs to be bound with a constant lvalue reference or an rvalue reference.
So modify the friend function tofriend ostream& operator(ostream& ostr, const Point& p)
Then the error was resolved smoothly!
- Forum
- Beginners
- Unexpected E0349 error
Unexpected E0349 error
I have two instances of the following code just built in two different projects on the same visual studio package on the same machine at approximately the same time. On the first project the code compiled and ran with no problems.
I created a new project and entered the code but the second attempt failed giving E0349 errors ‘no operator «>>» and «<<» matchs these operands along with a number of other errors.
I can find no references to this behavior on the internet or any of my manuals.
I have retyped the errant code numerous times with the same results.
I have Copied and pasted the code into the second window, still fails.
I created a third project and pasted the code. Still fails
I suspect I am making at least one stupid mistake but I cannot find it.
Any help you could give would be greatly appreciated.
Both instances of the code look identical to me down to the line counts.
I have a screen shot of both windows side by side if that would help.
.
|
|
Try adding #include <string> and moving «using namespace std» to just after the includes.
And remember, when dealing with a bunch of errors, deal with the very first one first (scroll back if necessary to find it). Other errors may just be a cascade of problems due to the first.
Last edited on
Topic archived. No new replies allowed.
Вход в кабинет MTS
Вход в кабинет TELE2
Вход в кабинет Beeline
Вход в кабинет Megafon
Вход в кабинет Ростелеком
- Forum
- Beginners
- Unexpected E0349 error
Unexpected E0349 error
I have two instances of the following code just built in two different projects on the same visual studio package on the same machine at approximately the same time. On the first project the code compiled and ran with no problems.
I created a new project and entered the code but the second attempt failed giving E0349 errors ‘no operator «>>» and «<<» matchs these operands along with a number of other errors.
I can find no references to this behavior on the internet or any of my manuals.
I have retyped the errant code numerous times with the same results.
I have Copied and pasted the code into the second window, still fails.
I created a third project and pasted the code. Still fails
I suspect I am making at least one stupid mistake but I cannot find it.
Any help you could give would be greatly appreciated.
Both instances of the code look identical to me down to the line counts.
I have a screen shot of both windows side by side if that would help.
.
|
|
Try adding #include <string> and moving «using namespace std» to just after the includes.
And remember, when dealing with a bunch of errors, deal with the very first one first (scroll back if necessary to find it). Other errors may just be a cascade of problems due to the first.
Last edited on
Topic archived. No new replies allowed.