C++ OOP 学习
类知识点:
(有空回来补充)
Critter Caretaker 源码
#include <iostream>
using namespace std;
class Critter
{
public:
Critter(int hunger = 0, int boredom = 0);
void Talk();
void Eat(int food = 4);
void Play(int fun = 4);
void GetStatus();
int GetHunger() const;
int GetBoredom() const;
private:
int m_Hunger;
int m_Boredom;
int GetMood() const;
void PassTime(int time = 1);
};
Critter::Critter(int hunger, int boredom) :
m_Hunger(hunger),
m_Boredom(boredom)
{}
inline int Critter::GetMood() const
{
return (m_Hunger + m_Boredom);
}
void Critter::PassTime(int time)
{
m_Hunger += time;
m_Boredom += time;
}
void Critter::Talk()
{
cout << "I'm a critter and I feel ";
int mood = GetMood();
if (mood > 15)
{
cout << "mad.\n";
}
else if (mood > 10)
{
cout << "frustrated.\n";
}
else if (mood > 5)
{
cout << "okay.\n";
}
else
{
cout << "happy.\n";
}
PassTime();
}
void Critter::Eat(int food)
{
cout << "Brruppp.\n";
m_Hunger -= food;
if (m_Hunger < 0)
{
m_Hunger = 0;
}
PassTime();
}
void Critter::Play(int fun)
{
cout << "Wheee!\n";
m_Boredom -= fun;
if (m_Boredom < 0)
{
m_Boredom = 0;
}
PassTime();
}
void Critter::GetStatus()
{
cout << "Your critter's hunger: " << m_Hunger << endl;
cout << "Your critter's boredom: " << m_Boredom << endl;
PassTime();
}
int Critter::GetHunger() const
{
return m_Hunger;
}
int Critter::GetBoredom() const
{
return m_Boredom;
}
int main()
{
Critter crit;
crit.Talk();
int choice;
do
{
cout << "\nCritter Caretaker\n\n";
cout << "0 - Quit\n";
cout << "1 - Listen to your critter\n";
cout << "2 - Feed your critter\n";
cout << "3 - Play with your critter\n";
cout << "4 - Get critter's status\n\n";
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 0:
cout << "Good-bye.\n";
break;
case 1:
crit.Talk();
break;
case 2:
crit.Eat();
break;
case 3:
crit.Play();
break;
case 4:
crit.GetStatus();
break;
default:
cout << "\nSorry, but " << choice << " isn't a valid choice.\n";
}
if (crit.GetHunger() >= 10)
{
cout << "\"I am close to dieeee!\"" << endl;
}
if (crit.GetBoredom() >= 15)
{
cout << "\"I am too unhappy to maintain myself!\"" << endl;
}
if (crit.GetHunger() >= 15 || crit.GetBoredom() >= 20)
{
cout << "\n\n Oh no! Your critter die! \n\n --G--A--M--E-- --O--V--E--R-- \n\n";
break;
}
cout << "------n-e-x-t----r-o-u-n-d------" << endl;
} while (choice != 0);
return 0;
}