У меня есть этот код на Visual C++ 2010
#include <iostream>
#include <string>
using namespace std;
class Human {
private:
int magic;
int health;
string name;
public:
int GetMagic() const;
int GetHealth() const;
Human(int, string);
~Human();
};
//helper
int Human::GetHealth() const {
cout <<"This returns Human::health" << endl;
return Human::health;
}
int Human::GetMagic() const {
cout <<"This returns this->magic"<< endl;
return this->magic;
}
//con/destructor
Human::Human(int a, int b, string c): health(a), magic(b), name(c)
{
cout<<c<<" is born!"<<endl;
}
Human::~Human()
{
cout <<this->name << " is killed!" << endl;
}
int main (){
Human lucife(20,10,"Lucife");
cout << lucife.GetHealth()<<endl;
cout << lucife.GetMagic()<<endl;
lucife.~Human();
cout << lucife.GetHealth()<<endl;
cout << lucife.GetMagic()<<endl;
cout<<endl;
lucife.~Human();
system("pause");
}
И когда я запускаю его:
Lucife is born!
This returns Human::health;
20
This returns this->magic
10
Lucife is killed!
This returns Human::health
20
This returns this->magic
10
is killed!
У меня есть 3 вопроса:
- После того, как я убил экземпляр "lucife" в первый раз, почему 2 метода GetHealth() и GetMagic() все еще работали?
- Во второй раз я вызвал ~Human() для экземпляра "lucife", почему он не распечатал "Lucife убит!" как в первый раз? Что именно здесь произошло? Значение имени удалено?
- Означает ли return Human::health и return this->health одно и то же? Я пробовал и вижу, что разницы нет. Я думаю, что оба они возвращают работоспособность экземпляра, для которого был вызван метод (в данном случае «lucife»).
Большое спасибо Вам