【问题标题】:How to specify a type parameter using <> to create a template class [closed]如何使用 <> 指定类型参数来创建模板类 [关闭]
【发布时间】:2016-01-13 17:43:35
【问题描述】:

我有这个代码:

class Grid {
public:
    vector<vector<int> > grid;
    int width;
    int height;

    Grid (int width, int height) width(width), height(height) {
        ...
    }
};

它创建了一个名为Grid 的类,它是一个二维整数数组。然而,问题是,目前它只能是整数,但我想要它,所以它有点像std::vector 类,您可以在其中使用&lt;&gt; 括号来选择类型它将存储。我的问题是,我如何在 my 类中使用这些,以便将所有当前的 ints 替换为任何其他类。

另外,你可能会说去查一下,但我试过了,但我什么也找不到,可能是因为我不知道要搜索什么,所以如果有人能给我一个关于这甚至叫什么的想法,那就'也会有帮助的。

【问题讨论】:

  • 阅读一本关于template-s 的好书programming using C++。但是教给你这个答案太长了。所以你的问题太笼统了......
  • 不,我的问题是我需要创建任何类型的Grid
  • 使网格成为模板
  • 在你的类定义顶部放“template”。您还必须将它放在类主体之外定义的任何方法上。 cprogramming.com/tutorial/templates.html
  • Templates。还有什么?

标签: c++ class vector


【解决方案1】:

您似乎只想模板化您的 Grid 类:

template <typename T>
class Grid {
  public:
    vector<vector<T> > grid;

    // initialize the vector with the correct dimensions:
    Grid (int width, int height)
        : grid(width, vector<double>(height)) {}
};

然后实例化:

Grid<double> g(x, y);

这将创建一个Grid 对象,其中Tdouble

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多