0

我正在尝试创建简单的项目来学习 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.");
}

当我以前将所有内容都放在一个文件中时,它运行良好,但我认为这不是一个好习惯,我想学习这一点。如果有人可以提供帮助,我会很高兴。

4

2 回答 2

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只是一个约定。

于 2013-06-06T07:41:13.473 回答
3

将您的类拆分为单独的标题。

然后,您将拥有:

两个都

class Bot{
    //...
};

GrumpyBot.h

#include "Bot.h"

class GrumpyBot : public Bot{
    //...
};

并为每个类保留一个 .cpp 文件。然后每个 .cpp 都包含其对应的类的标头。

附带说明一下,尽量避免using namespace std;在标头中使用,这不是一个好习惯,因为它将为标头进入的整个翻译单元启用此指令,并且可能很危险(它可能导致名称冲突问题)。

于 2013-06-06T07:43:48.493 回答