首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >作为参数的C++类类型

作为参数的C++类类型
EN

Stack Overflow用户
提问于 2011-10-24 18:34:26
回答 1查看 23.8K关注 0票数 7

如果我有一个接口和许多实现这个接口的类,那么现在我可以将类的类型而不是对象的类型作为参数传递吗?

就像这样:

代码语言:javascript
运行
复制
Interface *creatClass(class : Interface){
    return new class();
}

编辑:

代码语言:javascript
运行
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-10-24 18:37:05

它叫"Template“。

代码语言:javascript
运行
复制
template <class T>
T *creatClass(){
    return new T();
}

你得这样称呼它:

代码语言:javascript
运行
复制
class InterfaceImpl : public Interface {...};
// ...
InterfaceImpl *newImpl = creatClass<InterfaceImpl>();

编辑的

您也可以尝试这样做,以确保只创建Interface的实例

代码语言:javascript
运行
复制
template <class T>
Interface *creatClass(){
    return new T();
}

编辑到编辑

我试过这个测试代码:

代码语言:javascript
运行
复制
#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();
}

就像预期的那样。您必须在类定义中出现其他一些编码错误。调试它,它与您的原始问题无关。

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7880153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档