我正在尝试创建简单的项目来学习 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;
}
现在我不知道如何拆分为头文件和 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.");
}
当我以前将所有内容都放在一个文件中时,它运行良好,但我认为这不是一个好习惯,我想学习这一点。如果有人可以提供帮助,我会很高兴。