我正在尝试创建简单的项目来学习C ++中的头文件和继承。 我创建了头文件:
Bot.h
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
class Bot {
public:
Bot();
~Bot();
bool initialized;
string getRandomMessage();
string getName();
protected:
vector<string> messages;
string name;
};
然后我有Bot.cpp
我在哪里
/**
*
* @return random message from Bot as string
*/
string Bot::getRandomMessage() {
int r = static_cast<double> (std::rand()) / RAND_MAX * this->messages.size();
return messages[r];
}
/**
*
* @return bot's name as string
*/
string Bot::getName() {
return this->name;
}
现在我无法弄清楚,如何分割成header和cpp文件以及如何处理包含和其他东西以使它在我继承的类中工作,我已经实现了这样:
/**
* Specialized bot, that hates everything and everybody.
*/
class GrumpyBot : public Bot {
public:
GrumpyBot();
};
/**
* Default constructor for GrumpyBot
*/
GrumpyBot::GrumpyBot() {
initialized = true;
this->name = "GrumpyBot";
messages.push_back("I hate dogs.");
messages.push_back("I hate cats.");
messages.push_back("I hate goats.");
messages.push_back("I hate humans.");
messages.push_back("I hate you.");
messages.push_back("I hate school.");
messages.push_back("I hate love.");
}
当我以前把它全部放在一个文件中时,它运作良好,但我不认为这是一个好习惯,我想学习这个。如果有人可以提供帮助,我会很高兴。
答案 0 :(得分:6)
你已经为Bot
做了这个,并且它与子类相同:
GrumpyBot.h
#ifndef GRUMPY_BOT_H //this will prevent multiple includes
#define GRUMPY_BOT_H
#include "Bot.h"
class GrumpyBot : public Bot {
public:
GrumpyBot();
};
#endif
GrumpyBot.cpp
#include "GrumpyBot.h"
GrumpyBot::GrumpyBot() {
initialized = true;
this->name = "GrumpyBot";
messages.push_back("I hate dogs.");
messages.push_back("I hate cats.");
messages.push_back("I hate goats.");
messages.push_back("I hate humans.");
messages.push_back("I hate you.");
messages.push_back("I hate school.");
messages.push_back("I hate love.");
}
需要ifndef/define/endif
机制,以便编译器在解析包含头的另一个头时不再包含头。您还必须更改Bot.h
,使用HEADER_NAME_H
只是一种惯例。
答案 1 :(得分:3)
将您的班级拆分为单独的标题。
然后,你将拥有:
Bot.h
class Bot{
//...
};
GrumpyBot.h
#include "Bot.h"
class GrumpyBot : public Bot{
//...
};
并为每个类保留一个.cpp文件。然后每个.cpp包含其对应的类'标题。
在旁注中,尽量避免在标题中使用using namespace std;
,这是不太好的做法,因为它会为整个翻译单元启用此指令,并且它可能是危险的(它可能是危险的)导致名称冲突问题)。