I need help, I need to implement a class with sets and add and subtract it for them, the problem is that I cannot display the results

#include <iostream> #include <time.h> using namespace std; class NewClass { public: int *p; short int _size; public: NewClass(int A) :_size(A) // NewClass P(5); { p = new int[_size]; for (int i = 0; i < A; i++) p[i] = rand() % 10; }; NewClass(int *p1) { p = p1; }; // int A[5]{1,2,3,4,5} ; NewClass Mas(A); NewClass() {}; NewClass operator +(NewClass& value) { int size1 = _size; NewClass mas; for (int i = 0; i < size1; ++i) { if (p[i] == value.p[i]) { value.p[i] = value.p[i + 1]; size1--; } } mas = new int[size1 + _size]; for (int i = 0; i < _size; ++i) mas.p[i] = p[i]; for (int i = _size; i < (_size + size1); ++i) mas.p[i] = value.p[i]; return mas; } NewClass operator -(NewClass& value) { int size1 = _size, size2 = _size; for (int i = 0; i < size1; i++) { if (p[i] == value.p[i]) { value.p[i] = value.p[i + 1]; p[i] = p[i + 1]; size1--; size2--; } } NewClass mas; mas = new int[size1 + _size]; for (int i = 0; i < size2; ++i) mas.p[i] = p[i]; for (int i = size2; i < (size2 + size1); ++i) mas.p[i] = value.p[i]; return mas; } void show() { for (int i = 0; i < _size; i++) { std::cout << p[i] << " "; } std::cout << "\n"; }; }; int main() { int _size; cin >> _size; srand(time(0)); NewClass A(_size); NewClass B(_size); NewClass C(); A.show(); B.show(); int k; cout << "Enter 1 to sum or 2 to diff -> "; cin >> k; if (k == 1) A + B; if (k == 2) A - B; return 0; } 

    1 answer 1

    I have not seen such a terrible, illiterate code for a long time. To you a lot of complaints. I tried to start it at home, but I understand that you can only bring it to mind by rewriting it completely. How did it compile at all? Recommendations to you:

    1. Align the code, follow the style, read your code terrible flour. Call the variables as informative as possible.

    2. In loops instead of i++ use ++i .

    3. Explicitly separate the declaration and function definition. And if, for some reason, you don’t want to, at least don’t put extras ; after square brackets. This can lead to an undefined result when compiled.

    4. Almost everywhere you allocate memory for *p , but you don’t release it anywhere. Watch your memory, select and destroy it when necessary, I don’t even see a destructor here.

    5. Do not use cycles to copy data between pointers, there is a great function memcpy

    6. For your class, NORMALLY declare all the necessary constructors, operators. You use an assignment operator, but it is not explicitly declared anywhere.

    7. In constructors, copy data to your class, and not just assign pointers.

    8. To transfer a string to std::cout use std::endl . On the Internet you can find information why.

    9. Make your classes universal, patterned.

    10. Remove the show function from the class body, it violates the principles of OOP design.

    It's too early for you to write your own classes.