Mar*_*cek 0 c++ inheritance header
我正在尝试创建简单的项目来学习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;
};
Run Code Online (Sandbox Code Playgroud)
然后我就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;
}
Run Code Online (Sandbox Code Playgroud)
而现在我无法弄清楚,如何分割成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.");
}
Run Code Online (Sandbox Code Playgroud)
当我以前把它全部放在一个文件中时,它运行良好,但我认为这不是一个好习惯,我想学习这个.如果有人可以提供帮助,我会很高兴.
你已经完成了它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
Run Code Online (Sandbox Code Playgroud)
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.");
}
Run Code Online (Sandbox Code Playgroud)
ifndef/define/endif需要该机制,以便编译器在解析包含它的另一个时不再包含头.你必须改变你Bot.h,使用HEADER_NAME_H只是一个约定.