抽象类C++中的变量

wya*_*att 4 c++ abstract-class

我有一个抽象类CommandPath,以及一些派生类,如下所示:

class CommandPath {
    public:
        virtual CommandResponse handleCommand(std::string) = 0;
        virtual CommandResponse execute() = 0;
        virtual ~CommandPath() {}
};

class GetTimeCommandPath : public CommandPath {
    int stage;
    public:
        GetTimeCommandPath() : stage(0) {}
        CommandResponse handleCommand(std::string);
        CommandResponse execute();
};
Run Code Online (Sandbox Code Playgroud)

所有派生类都有成员变量'stage'.我想在所有这些中构建一个函数,它以相同的方式操纵'stage',所以我没有多次定义它,而是认为我将它构建到父类中.我将'stage'从所有派生类的私有部分移动到CommandPath的受保护部分,并添加了如下函数:

class CommandPath {
    protected:
        int stage;
    public:
        virtual CommandResponse handleCommand(std::string) = 0;
        virtual CommandResponse execute() = 0;
        std::string confirmCommand(std::string, int, int, std::string, std::string);
        virtual ~CommandPath() {}
};

class GetTimeCommandPath : public CommandPath {
    public:
        GetTimeCommandPath() : stage(0) {}
        CommandResponse handleCommand(std::string);
        CommandResponse execute();
};
Run Code Online (Sandbox Code Playgroud)

现在我的编译器告诉我构造函数行,没有派生类有成员'stage'.我的印象是受保护的成员对派生类是可见的?

所有类中的构造函数都是相同的,所以我想我可以将它移动到父类,但我更关心的是找出派生类无法访问变量的原因.

此外,由于以前我只使用父类用于纯虚函数,我想确认这是添加要由所有派生类继承的函数的方法.

ros*_*dia 14

试试这个:

class CommandPath {
protected:
  int stage;
public:
  CommandPath(int stage_) : stage(stage_) {}
};

class GetTimeCommandPath : public CommandPath {
public:
  GetTimeCommandPath(int stage_) : CommandPath(stage_) {}
};
Run Code Online (Sandbox Code Playgroud)

(为简洁起见,省略了额外的代码).

您不能在父类的成员上使用初始化列表,只能使用当前的成员.如果这是有道理的.

  • +1尽管省略`_stage`变量中的前导`_`是完全安全的. (2认同)