本文介绍了C++ 抽象基类构造函数/析构函数 - 一般正确性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想要一个 C++ Interface,它在继承时必须被覆盖(如果可能的话).到目前为止,我有以下内容:

I would like to have a C++ Interface that must be overridden (if this is possible) when inherited. So far, I have the following:

class ICommand{

public:
    //  Virtual constructor. Needs to take a name as parameter
    //virtual ICommand(char*) =0;
    //  Virtual destructor, prevents memory leaks by forcing clean up on derived classes?
    //virtual ~ICommand() =0;
    virtual void CallMe() =0;
    virtual void CallMe2() =0;
};

class MyCommand : public ICommand
{
public:
    // Is this correct?
    MyCommand(char* Name) { /* do stuff */ }
    virtual void CallMe() {}
    virtual void CallMe2() {}
};

我特意留下了我认为应该在ICommand 中实现构造函数/析构函数的方式.我知道如果我删除评论,它将无法编译.请有人:

I have purposely left how I think the constructor/destructor's should be implemented in ICommand. I know if I remove the comments, it will not compile. Please could someone:

  1. 告诉我如何在 ICommand 中声明构造函数/析构函数,以及如何在 MyCommand
  2. 中使用它们
  3. 我是否在 ICommand 中正确设置,以便 MyCommand 必须覆盖 CallMeCallMe2.莉>
  1. Show me how to declare the constructor/destructor's in ICommand and how they are meant to be used in MyCommand
  2. Have I set things up correctly in ICommand so that MyCommand must override CallMe and CallMe2.

推荐答案

C++ 不允许使用虚拟构造函数.一个简单的实现(没有虚拟构造函数)看起来像这样:

C++ does not allow for virtual constructors. A simple implementation (without the virtual constructor) would look something like this:

class ICommand {
public:
    virtual ~ICommand() = 0;
    virtual void callMe() = 0;
    virtual void callMe2() = 0;
};

ICommand::~ICommand() { } // all destructors must exist

请注意,即使是纯虚拟析构函数也必须被定义.

Note that even a pure virtual destructor must be defined.

具体的实现与您的示例完全一样:

A concrete implementation would look exactly like your example:

class MyCommand : public ICommand {
public:
    virtual void callMe() { }
    virtual void callMe2() { }
};

您有几个选项对于构造函数.一种选择是禁用 ICommand 的默认构造函数,这样子类将必须实现一个调用你的 ICommand 构造函数的构造函数:

You have a couple of options for the constructor. One option is to disable the default constructor for ICommand, so that subclasses will have to implement a constructor that calls your ICommand constructor:

#include <string>

class ICommand {
private:
    const std::string name;
    ICommand();
public:
    ICommand(const std::string& name) : name(name) { }
    virtual ~ICommand() = 0;
    virtual void callMe() = 0;
    virtual void callMe2() = 0;
};

ICommand::~ICommand() { } // all destructors must exist

一个具体的实现现在看起来像这样:

A concrete implementation would now look something like this:

class MyCommand : public ICommand {
public:
    MyCommand(const std::string& name) : ICommand(name) { }
    virtual void callMe() { }
    virtual void callMe2() { }
};

这篇关于C++ 抽象基类构造函数/析构函数 - 一般正确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:34