该项目由三个文件源文件构成,headerfile.h作为头文件用来定义类,headerfuc.cpp为类中的函数提供定义,test.cpp为主函数进行调用。
该程序主要练习了类的构造函数,析构函数,函数重载,this指针,值的引用,类的设计,还有其他巴拉巴拉的乱七八糟的东西。我最近在看c++primerplus,虽然一直在看但是缺乏练习,该程序是第一个练习。
该程序主要模拟了魔塔游戏中的攻击与防御机制。以下为代码实现。
//headerfile.h头文件
#ifndef textheader
#define textheader
#include<string>
class Properties
{
private:
std::string name;
int atk;
int def;
int health;
public:
Properties();
Properties(std::string name_, int atk_ = 30, int def_ = 17, int health_ = 70);
~Properties();
void show()const;
void fight(Properties& p2);
};
#endif
//headerfuc.cpp c++源文件
#include<iostream>
#include"headerfile.h"
Properties::Properties()
{
name = "no name";
atk = 20;
def = 20;
health = 100;
}
Properties::Properties(std::string name_, int atk_, int def_, int health_)
{
name = name_;
atk = atk_;
def = def_;
health = health_;
}
Properties::~Properties()
{
std::cout << "Bye," <<name<<"!"<< std::endl;
}
void Properties::show()const
{
using std::cout;
using std::endl;
cout << "The properties of "<<name<<" are as follows"<<endl;
cout << "\tattack= " << atk;
cout << "\tdefence= " << def;
cout << "\thealth= " << health << endl<<endl;
}
void Properties::fight(Properties& p2)
{
using std::cout;
using std::endl;
int round = 1;
Properties& p1 = *this;
std::cout << "the " << p1.name << " started a fight against the " << p2.name << ",the details are as follows:" << endl;
int p1atk = p1.atk - p2.def;
int p2atk = p2.atk - p1.def;
while (p2.health > 0 && p1.health > 0)
{
cout <<endl<<"round :"<<round++<<" begin!" << endl;
p2.health -= p1atk > 0 ? p1atk : 0;
cout << p2.name << " get " << p1atk << " damage,and HP remains\t " << p2.health<<endl;
if (p2.health <= 0)
break;
p1.health -= p2atk > 0 ? p2atk : 0;
cout << p1.name << " get " << p2atk << " damage,and HP remains\t " << p1.health<<endl;
}
if (p2.health <= 0)
cout << p2.name << " has been defeated, and " << p1.name << " won!"<<endl<<endl;
else
cout <<"Oops!" << p1.name << " has been defeated, now the " << p2.name << " won!" << endl<<endl;
}
//test.cpp
#include<iostream>
#include<vector>
#include"headerfile.h"
using namespace std;
int main()
{
system("color 0B");
Properties player1=Properties("jack");
Properties player2("Rose", 26, 12, 300);
Properties player3 = Properties();
player1.show();
player2.show();
player3.show();
player1.fight(player2);
player1.show();
player2.show();
player3.fight(player2);
player2.show();
player3.show();
return 0;
}
以上为代码实现。下图为该代码的部分运行图。
总的来说,类是用户定义的类型,对象则是类的示例。类与对象编程强调了面向对象的编程思想。程序员使用OOP方法解决编程问题,第一步是根据它与程序之间的接口来描述数据,从而指定如何使用数据。然后设计一个类来实现该接口。类与对象的好处之一是使程序便于维护,开发者可以随意的对程序的任何部分做独立的改进,而不必担心这样做会导致意外的不良影响。