我正试图在医院做一个小游戏。这是代码:
首先是标题:
#ifndef Hospital_Patient_h
#define Hospital_Patient_h
class Patient
{
public:
Patient();
bool cured();
bool died();
bool treatable();
void treat();
void untreated();
char consonant();
char vowel();
std::string getName();
int age;
int health;
std::string name;
bool operator==(const Patient &other)const;
};
#endif
这是cpp:
#include <iostream>
#include <string>
#include "Patient.h"
using namespace std;
char CONSONANTS[] =
{'b','c','d','f','g','h','j','k','l','m','n','p','r','s','t','v','z', '\0'};
char VOWELS[] =
{'a','e','i','o','u', '\0'};
//generates a patient with initial health, a name, and an age from 10-79
Patient::Patient()
{
int a= rand() % 80 + 10;
health= 50;
name= getName();
age= a;
}
bool Patient::cured() {
return health >= 100;
}
bool Patient::died() {
return health <= 0;
}
//treatable if not dead and not cured
bool Patient::treatable() {
return !died() && !cured();
}
void Patient::treat() {
if(treatable()) health= min(health + 10, 100);
}
void Patient::untreated() {
if(treatable()) health= max(health - 1, 0);
}
char Patient::consonant()
{
int index = rand() % 17; //CONSONANTS.size();
return CONSONANTS[index];//rand.nextInt(CONSONANTS.length)];
}
char Patient::vowel()
{
int index = rand() % 5; //VOWELS.size();
return VOWELS[index];//rand.nextInt(VOWELS.length)];
}
//generate a random name
string Patient::getName(){
string s;
s+=toupper(consonant());
s+= vowel();
s+=consonant();
s+=vowel();
if (rand() % 3 == 0) {
s+=consonant();
}
if (rand() % 3 == 0) {
s+=consonant();
s+=vowel();
}
s+=(' ');
s+=toupper(consonant());
s+=vowel();
if (rand() % 3 == 0) {
s+=consonant();
}
s+=consonant();
s+=vowel();
if (rand() % 3 == 0) {
s+=consonant();
}
if (rand() % 3 == 0) {
s+=consonant();
s+=vowel();
}
return s;
}
//overload ==
bool Patient::operator==(const Patient &other)const{
//compare each room's room number field
return (this->age == other.age && this->name == other.name);
}
在每个函数之后到目前为止,我得到一个错误,称“重新定义'函数名'
我也遇到了构造函数的问题,并为标头中定义的变量赋值。由于某种原因,标题也不喜欢std ::我知道我不应该在标题中使用名称空间。
答案 0 :(得分:0)
尝试将#include <string>
添加到Patient.h的最顶层。当我这样做时它为我编译。
答案 1 :(得分:0)
只是预感,您在其中一个文件中添加了Patient.cpp
而不是Patient.h
。