如何传递一个类作为参数 [英] How to pass a Class as Parameter

查看:91
本文介绍了如何传递一个类作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中有一种方法可以将类型(例如类)作为参数传递给函数?

这里有一个抽象的数据类和 manager 类。 manager 类包含 data 的派生类的对象的列表(或在此示例中为一个映射)。如 unique_ptr -from-different-classes>这个问题

Explanation why I need this: There is a abstract data class and a manager class. The manager class contains a list (or in this case a map) of objects of derived classes of data. I use unique_ptr for this as mentioned in the answer of this question.

class Data{}; // abstract

class Manager
{
    map<string, unique_ptr<Data>> List;
};

现在想象我要添加一个新的数据存储到管理器。

Now imagine I want to add a new data storage to the manager.

class Position : public Data
{
    int X;
    int Y;
}

我如何告诉管理器创建该类型的对象, unique_ptr 吗?

How could I tell the manager to create a object of that type and refer an unique_ptr to it?

Manager manager;
manager.Add("position data", Position);

在这种情况下,我需要传递类 Position 添加到管理器类的添加函数,因为我不想先创建一个实例,然后将其发送给管理器。

In this case I would need to pass the class Position to the add function of the manager class since I don't want to have to first create an instance and then send it to the manager.

然后,我如何将该类的对象添加到 List

And then, how could I add the object of that class to the List?

我不知道有没有办法在C ++。如果这不能轻易完成,我真的想看到一个解决方法。非常感谢!

I am not sure if there is a way of doing that in C++. If that can't be done easily I would really like to see a workaround. Thanks a lot!

推荐答案

您可以使用模板。在从 Data 派生的每个类型中,您将必须定义一个creator函数,其具有以下原型: Derived * create()。它将在内部调用(您也可以返回 unique_ptr ,但这将需要更多的内存)。

You can use templates. In each type deriving from Data you will have to define a 'creator' function, which have the following prototype: Derived* create(). It will be called internally (you can also return a unique_ptr, but that would requires more memory).

Ex :

struct Position: public Data
{
    // ...
    static Position* create()
    {
        return new Position();
    }
};

添加 p>

The Add method will be:

template<typename D>
void Add(String str)
{
    List.insert(std::make_pair(str, std::unique_ptr<Data>(D::create())));
}

然后你这样使用:

Manager manager;
manager.Add<Position>("position data");

EDIT

您还可以使用添加方法摆脱创建函数:

You can also get rid of the create functions, by using this Add method:

template<typename D>
void Add(String str)
{
    List.insert(std::make_pair(str, std::unique_ptr<Data>(new D())));
}

优点:数据结构代码中的代码更少。

Advantage: less code in data structure code.

不便:数据结构对其构建方式的控制较少。

Inconvenient: data structures have less control on how they're built.

这篇关于如何传递一个类作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆