C++ 引用与引用作为函数的参数
C++函数的三种传递方式为:值传递、指针传递和引用传递
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
写于浙江宁波
网友评论