Severity Code Description Project File Line Suppression State Error (active) E0349 no…
- User
Severity Code Description Project File Line Suppression State Error (active) E0349 no operator "-" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 169 Error (active) E0349 no operator "-" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 180 Error (active) E0349 no operator "-" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 216 Error (active) E0349 no operator "-" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 217 Error (active) E0349 no operator "-" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 218 Error (active) E0349 no operator "+" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 226 Error (active) E0349 no operator "-" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 227 Error (active) E0349 no operator "-" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 237 Error (active) E0349 no operator "+" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 241 Error (active) E0349 no operator "+" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 244 Error (active) E0349 no operator "-" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 256 Error (active) E0349 no operator "-" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 264 Error (active) E0349 no operator "-" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 272 Error (active) E0349 no operator "+" matches these operands OOP_LR7 C:\Users\student_112\Downloads\vs solution\OOP_LR7\main.cpp 277
#include #include using namespace std; // клас дати class Date { int day; // день int month; // місяць int year; // рік public: // конструктор Date(int dayl, int monthl, int yearl) { day = dayl; month = monthl; year = yearl; } // перевантажена операція введення з потоку friend istream& operator>>(istream& is, Date& d) { is >> d.day >> d.month >> d.year; return is; } // перевантажена операція виведення у потік friend ostream& operator<<(ostream& os, Date& d) { os << d.day << '.' << d.month << '.' << d.year << endl; return os; } }; // клас з інформацією про продукцію підприємства class Product { Date d; string code; string name; int count; double price; public: //конструктор Product(Date dl = Date(1, 3, 2012), string codel = "", string namel = "", int countl = 0, double pricel = 0) :d(dl) { code = codel; name = namel; count = countl; price = pricel; } // метод читання дати Date& getDate() { return d; } // метод читання коду string& getCode() { return code; } // метод читання назви string& getname() { return name; } // метод читання кількості int& getCount() { return count; } // метод читання ціни double& getPrice() { return price; } // перевантажена операція введення з потоку friend istream& operator>>(istream& is, Product& t) { is >> t.d >> t.code >> t.name >> t.count >> t.price; return is; } // перевантажена операція виведення у потік friend ostream& operator<<(ostream& os, Product& t) { os << t.d << ' ' << t.code << ' ' << t.name << ' ' << t.count << ' ' << t.price << endl; return os; } };
#define T Product //ітераторний клас class iter { protected: T* i; // вказівник на елемент даних public: //конструктор iter(T* il) : i(il) { } //конструктор копіювання iter(const iter& x) : i(x.i) { } //перевантажена операція присвоєння ітераторів iter& operator=(const iter& x) { i = x.i; return this; } // перевантажена операція розіменування ітератора T& operator() const { return *i; } // перевантажена операція префіксного інкременту ітератора iter& operator++() { ++i; return *this; } // перевантажена операція "не дорівнює" для порівняння ітераторів bool operator!=(const iter& x) const { return i != x.i; } // перевантаженя операцій додавання та віднімання ітераторів /iter& operator-(int a) { i - a; return this; }/ //... //... }; // клас складу виробів //контейер class Storage { T p; // вказівник на масив виробів int size; // кількість елементів масиву public: // конструктор Storage(int n = 1) { p = new T[size = n]; for (iter i = begin(); i != end(); ++i) *i = T(); } // конструктор копіювання Storage(const Storage& a) { p = new T[size = a.size]; for (iter i = begin(); i != end(); ++i) *i = a.p[i - begin()]; }
// деструктор ~Storage() { delete[]p; } // перевантажена операція присвоєння об'єктів Storage& operator=(const Storage& a) { if (this != &a) { delete[]p; p = new T[size = a.size]; for (iter i = begin(); i != end(); ++i) *i = a.p[i - begin()]; } return *this; } // перевантажена операція введення з потоку friend istream& operator>>(istream& is, Storage& s) { for (iter i = s.begin(); i != s.end(); ++i) is >> *i; return is; } // перевантажена операція виведення у потік friend ostream& operator<<(ostream& os, Storage& s) { for (iter i = s.begin(); i != s.end(); ++i) os << *i << ' '; os << endl; return os; } // метод обчислення вартості виробів заданого коду double cost(string code) { double v = 0; for (iter i = begin(); i != end(); ++i) if ((*i).getCode() == code) v += (*i).getCount() * (*i).getPrice(); return v; } // метод визначення значення ітератора перед масивом iter begin() { return iter(p); } // метод визначення значення ітератора поза масивом iter end() { return iter(p + size); } /////*****////// Storage& push_back(T x) { Storage temp = *this; delete[]p; p = new T[size += 1]; int j = 0; for (iter i = begin(); i != end() - 1; ++i) *i = temp.p[i - begin()]; iter i = end() - 1; *i = x; return *this; } Storage& push_front(T x) { Storage temp = *this; delete[]p; p = new T[size += 1]; for (iter i = begin() + 1; i != end(); ++i) *i = temp.p[i - begin() - 1]; iter i = begin(); *i = x; return *this; } Storage& insert(T x, int pos) { Storage temp = *this; delete[]p; p = new T[size += 1]; int j = 0; for (iter i = begin(); i != end() - pos; ++i) { *i = temp.p[j++]; } iter i = begin() + pos; *i = x; j -= pos - 1; for (iter i = begin() + pos + 1; i != end(); ++i) { *i = temp.p[j++]; } return *this; } Storage& pop_back() { Storage temp = *this; delete[]p; p = new T[size -= 1]; for (iter i = begin(); i != end(); ++i) *i = temp.p[i - begin()]; return *this; } Storage& pop_front() { Storage temp = *this; delete[]p; p = new T[size -= 1]; for (iter i = begin(); i != end(); ++i) *i = temp.p[i - begin() + 1]; return *this; } Storage& erase(int pos) { Storage temp = *this; delete[]p; p = new T[size -= 1]; int j = 0; for (iter i = begin(); i != end() - pos; ++i) { *i = temp.p[j++]; } j -= pos - 1; for (iter i = begin() + pos; i != end(); ++i) { *i = temp.p[j++]; } return *this; }};
// головна функція void main() {
//Ініціалізувати масив об'єктів класу за інд.завданням //... int n; cin >> n; Storage s(n); //Вивести зміст контейнеру //... //Додати новий елемент в кінець контейнеру //... //Вивести зміст контейнеру //... //Додати новий елемент на початок контейнеру //... //Вивести зміст контейнеру //... //Додати новий елемент у визначину позицію контейнеру //... //Вивести зміст контейнеру //... //Додати ще 2 рази любим з вищезастосованих методів //.. //Вивести зміст контейнеру //... //Видалити останій елемент контейнеру //.. //Вивести зміст контейнеру //... //Видалити перший елемент контейнеру //.. //Вивести зміст контейнеру //... //Видалити елемент контейнеру з визначеної позиції //.. //Вивести зміст контейнеру //...}
- Assistant
The compiler errors you're encountering (
E0349) indicate that theiterclass does not support the+and-operators for the operands you're using. Specifically, operations likeend() - 1orbegin() + 1are causing these errors because theiterclass lacks the necessary operator overloads to handle these expressions.Understanding the Problem
-
Iterator Operations in
StorageClass:- Methods like
push_back,push_front,insert,erase, etc., are using expressions such asend() - 1,begin() + 1, etc. - These operations assume that the
iterclass supports arithmetic operations with integers, which it currently does not.
- Methods like
-
iterClass Definition:- The
iterclass wraps a pointerT* ibut only overloads the*,++,!=, and assignment operators. - The arithmetic operators
+and-are either missing or incorrectly implemented (as seen in the commented-outoperator-).
- The
Solution
To resolve the errors, you need to properly overload the
+and-operators in theiterclass to handle arithmetic operations with integers. Here's how you can do it:-
Overload
operator+andoperator-foriterandint:- These operators will allow you to add or subtract an integer from an iterator, returning a new iterator instance.
-
Overload
operator-to Compute Distance Between Iterators (Optional):- If you need to compute the distance between two iterators (e.g.,
iter1 - iter2), you can overload theoperator-to return the difference as an integer.
- If you need to compute the distance between two iterators (e.g.,
-
Implementing the Overloads Correctly:
- Ensure that these operators return new instances of
iterrather than modifying the current instance. - Avoid returning by reference unless necessary.
- Ensure that these operators return new instances of
Updated
iterClass with Operator Overloads// Iterator class class iter { protected: T* i; // Pointer to the data element public: // Constructor iter(T* il) : i(il) { } // Copy constructor iter(const iter& x) : i(x.i) { } // Assignment operator iter& operator=(const iter& x) { i = x.i; return *this; } // Dereference operator T& operator*() const { return *i; } // Prefix increment operator iter& operator++() { ++i; return *this; } // Inequality operator bool operator!=(const iter& x) const { return i != x.i; } // Addition operator: iter + int iter operator+(int a) const { return iter(i + a); } // Subtraction operator: iter - int iter operator-(int a) const { return iter(i - a); } // Optional: Subtraction operator to find distance between two iterators int operator-(const iter& other) const { return static_cast<int>(i - other.i); } // Optional: Addition assignment operator iter& operator+=(int a) { i += a; return *this; } // Optional: Subtraction assignment operator iter& operator-=(int a) { i -= a; return *this; } };Explanation of the Overloads
-
iter operator+(int a) const:- Adds
ato the current iterator's pointer and returns a newiterinstance pointing to the new location.
- Adds
-
iter operator-(int a) const:- Subtracts
afrom the current iterator's pointer and returns a newiterinstance pointing to the new location.
- Subtracts
-
int operator-(const iter& other) const: (Optional)- Computes the distance between two iterators by subtracting their pointers.
-
iter& operator+=(int a)anditer& operator-=(int a): (Optional)- Allows modifying the current iterator by adding or subtracting an integer.
Applying the Fix to Your Code
With these operator overloads in place, the expressions in your
Storageclass methods likepush_back,push_front,insert, anderasewill work as expected. Here's an example of howpush_backwould utilize the newoperator-:Storage& push_back(T x) { Storage temp = *this; delete[] p; p = new T[size += 1]; int j = 0; for (iter i = begin(); i != end() - 1; ++i) *i = temp.p[j++]; iter i = end() - 1; *i = x; return *this; }Additional Recommendations
-
Use Standard Iterators:
- Consider using standard library iterators (
std::vector,std::array, etc.) which already provide robust iterator support. - This can reduce the complexity of your code and avoid potential bugs related to manual memory management.
- Consider using standard library iterators (
-
Memory Management:
- Ensure that your
Storageclass handles memory correctly, especially in constructors, destructors, and assignment operators to prevent memory leaks or undefined behavior.
- Ensure that your
-
mainFunction Signature:- Change the signature of the
mainfunction fromvoid main()toint main()to adhere to the C++ standard.
- Change the signature of the
-
Error Handling:
- Add error handling for out-of-bound positions in methods like
insertanderaseto make your code more robust.
- Add error handling for out-of-bound positions in methods like
Final Corrected Code Snippet
Here's the updated
iterclass integrated into your existing code:// Iterator class class iter { protected: T* i; // Pointer to the data element public: // Constructor iter(T* il) : i(il) { } // Copy constructor iter(const iter& x) : i(x.i) { } // Assignment operator iter& operator=(const iter& x) { i = x.i; return *this; } // Dereference operator T& operator*() const { return *i; } // Prefix increment operator iter& operator++() { ++i; return *this; } // Inequality operator bool operator!=(const iter& x) const { return i != x.i; } // Addition operator: iter + int iter operator+(int a) const { return iter(i + a); } // Subtraction operator: iter - int iter operator-(int a) const { return iter(i - a); } // Optional: Subtraction operator to find distance between two iterators int operator-(const iter& other) const { return static_cast<int>(i - other.i); } // Optional: Addition assignment operator iter& operator+=(int a) { i += a; return *this; } // Optional: Subtraction assignment operator iter& operator-=(int a) { i -= a; return *this; } };By implementing these operator overloads, your
iterclass will support the necessary arithmetic operations, resolving the compiler errors you encountered.If you continue to face issues or have further questions, feel free to ask!
-