C++ 引用與引用作為函數(shù)的參數(shù)
C++函數(shù)的三種傳遞方式為:值傳遞吞滞、指針傳遞和引用傳遞
C++ 上課習題
#include <iostream>
using namespace std;
class Zombie
{
private:
int _strength;
public:
Zombie(int strength)
{
_strength = strength;
}
int getStrength()
{
return _strength;
}
void setStrength(int newStrength)
{
_strength += newStrength;
}
};
class Human
{
private:
int _blood;
public:
Human(int blood)
{
_blood = blood;
}
void attackbyZombie(Zombie &zombie) //pass by ref
{
_blood -= zombie.getStrength();
zombie.setStrength(zombie.getStrength());
}
int getblood()
{
return _blood;
}
};
int main() {
Zombie* zombie = new Zombie(5);
Human* human = new Human(20);
cout << zombie->getStrength()<<endl;
human->attackbyZombie(*zombie);
cout << zombie->getStrength() <<endl;
delete(zombie);
delete(human);
return 0;
}
劉月林
2019/03/20
寫于浙江寧波