Pytanie: rozumiem o co chodzi w filozofii operatora przypisania "operator=",ale nie bardzo rozumiem ideę linijki "if (this==&rhs) return *this;" Po prostu jakoś mi się to w głowie kiełbasi. Co ta linijka daje oraz dlaczego są przyrównane do siebie this z &rhs'em?
class Cat{
public:
Cat();
int GetAge(){ return *itsAge; }
int GetWeight(){ return *itsWeight; }
void SetAge(int age){ *itsAge=age; }
Cat operator=(Cat &);
private:
int *itsAge;
int *itsWeight;
};
Cat::Cat()
{
itsAge=new int;
itsWeight=new int;
*itsAge=5;
*itsWeight=9;
cout <<"adres thisa: "<<this<<endl;
}
Cat Cat::operator=(Cat & rhs)
{
if (this==&rhs) return *this;
*itsAge=rhs.GetAge();
*itsWeight=rhs.GetWeight();
cout <<"adres rhs: "<<&rhs<<endl;
return *this;
}
int main()
{
char znak=0;
Cat Mruczek;
cout <<"bierzacy wiek mruczka: "<<Mruczek.GetAge()<<endl;
cout <<"adres Mruczka: "<<&Mruczek<<endl;
Cat filemon;
filemon.SetAge(5);
cout <<"bierzacy wiek filemona: "<<filemon.GetAge()<<endl;
cout <<"adres filemona: "<<&filemon<<endl;
filemon.operator=(Mruczek);
//tu może być też oczywiscie filemon=Mruczek;
cout <<"wiek filemona: "<<filemon.GetAge()<<endl;
cout <<"adres filemona: "<<&filemon<<endl;
cout <<"koniec?: "<<endl;
while(1)
{
cin>>znak;
if (znak!='k') cout <<"to musi byc k: "<<endl;
else exit(0);
}
return 0;
}