Witam.
Mam problem z poniższym programem - zwraca błąd naruszenia pamięci.
Problem dotyczy operatora porównania.
Ma ktoś pomysł jak poprawić ten program?
#include <iostream>
struct A1
{
A1() : x(0), y(0) {}
A1(int x, int y)
{
this->x = x;
this->y = y;
}
int x;
int y;
};
class FirstClass
{
A1* a1;
public:
FirstClass()
: a1(nullptr) {}
FirstClass(int x, int y)
{
a1 = new A1(x, y);
}
~FirstClass()
{
delete a1;
}
int operator==(const FirstClass& rhs)
{
return (a1->x == rhs.a1->x && a1->y == rhs.a1->y);
}
FirstClass& operator=(const FirstClass& rhs)
{
if (this != &rhs)
{
delete a1;
a1 = nullptr;
a1 = new A1(rhs.a1->x, rhs.a1->y);
}
return *this;
}
};
class SecondClass
{
FirstClass firstClass;
public:
SecondClass() {}
~SecondClass() {};
void run(const FirstClass& firtsClass)
{
if (this->firstClass == firstClass)
{
std::cout << "The same !" << std::endl;
return;
}
else
std::cout << "Different !" << std::endl;
this->firstClass = firstClass;
}
};
int main()
{
FirstClass firstClass(1, 2);
SecondClass secondClass;
secondClass.run(firstClass);
return 0;
}