簡體   English   中英

C ++類類型作為參數

[英]C++ class type as argument

如果我有一個接口和許多實現此接口的類,我現在可以僅作為參數傳遞類的類型而不是對象嗎?

這樣的事情:

Interface *creatClass(class : Interface){
    return new class();
}

編輯:

template <class T>
IFrame *creatClass(){
    return new T();
}

void dfg(){
    IFrame *lol = creatClass<Button>();
}

error C3206: 'creatClass' : invalid template argument for 'Dist_Frame', missing template argument list on class template 'Button'

PS。 Button繼承IFrame

它被稱為“ 模板 ”。

template <class T>
T *creatClass(){
    return new T();
}

你必須這樣稱呼它:

class InterfaceImpl : public Interface {...};
// ...
InterfaceImpl *newImpl = creatClass<InterfaceImpl>();

編輯

您也可以嘗試這樣做,以確保您只創建Interface實例:

template <class T>
Interface *creatClass(){
    return new T();
}

編輯您的編輯

我試過這個測試代碼:

#include <iostream>
using namespace std;

class IFrame{
   public:
      virtual void Create() =0;
};

class Button : public IFrame{
    public:

       virtual void Create(){ cout << "In Button" << endl;};
};

template <class T>
IFrame *creatClass(){
    return new T();
}


int main()
{
    IFrame *lol = creatClass<Button>();
    lol->Create();
}

完全按預期工作。 您的類定義中必須存在其他一些編碼錯誤。 調試它,它與你原來的問題無關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM