2011-12-14 127 views
13

最近我作爲一個開發人員沉默寡言,所以我冒然冒險,拿到一本C++書籍,並學習如何正確地做事情。在我的腦海中,我知道我想要做什麼。我有效地想要一個Interface,當繼承時,必須被覆蓋(如果這是可能的?)。到目前爲止,我有以下幾點:C++抽象基類的構造函數/析構函數 - 一般正確性

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實施。我知道如果我刪除評論,它不會編譯。請替某人:

  1. 告訴我如何聲明構造/析構函數在ICommand以及它們是如何意味着MyCommand
  2. 要使用有我在ICommand正確設置的東西,使MyCommand必須覆蓋CallMeCallMe2

我希望我沒有錯過很簡單的東西...

+1

基本上你應該使用`std :: string`,而析構函數會是`{}`。還要了解構造函數初始化列表,並考慮是否不應該使用`const char *`。 – UncleBens 2011-12-14 23:59:43

回答

20

C++不允許虛構造。一個簡單的實現(沒有虛擬構造函數)將是這個樣子:即使是純虛析構函數must定義

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

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

注意。

一個具體的實施將看起來就像你的例子:

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

您有構造一對夫婦的options。一種選擇是禁用默認的構造函數ICommand,這樣子會來實現調用你的ICommand的一個構造:

#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 

具體實現,現在看起來是這樣的:

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

「C++不允許虛擬構造函數」我不確定這是正確的措辭。虛擬構造函數甚至意味着什麼,如果某種語言要實現它呢? (請注意,我說的是實際的構造函數,而不是構造相似的功能,只有這裏指的是靜態語言。) – 2011-12-15 00:17:56