【问题标题】:vector of template with two types具有两种类型的模板向量
【发布时间】:2015-10-21 02:48:11
【问题描述】:

我阅读了相关的帖子,但仍然无法弄清楚。 在我的 .h 文件中,我定义了一个模板类:

template <typename P, typename V>
class Item {
 public:
    P priority;
    V value;
    Item(P priority, V value): priority(priority), value(value){}
};

在我的主要功能中,我尝试制作具有特定类型的项目向量。

Item<int, string> Item1(18, "string 1");
Item<int, string> Item2(16, "string 2");
Item<int, string> Item3(12, "string 3");
Item<int, string> Item[3] = {Item1, Item2, Item3}
vector<Item<int, string> > Items(Item, Item + 3);

但我不断收到编译错误提示:

expected '(' for function-style cast or type construction
vector<Item<int, string> > Items(Item, Item + 9);
            ~~~^

【问题讨论】:

  • 你调用了你的数组Item,它与你的类Item同名,导致编译器变得混乱。
  • 数组后面也少了一个分号。
  • 你的代码风格不好,如果你使用Item作为一个类,请不要将名称Item用于其他用途。此外,如果Foo 是类名,则对象名应为foo。而且,你的 Items 是一个数组,对吧?让我们看看这个数组的声明。这不是编译器混淆,这是您的混淆。

标签: c++ templates vector


【解决方案1】:

这是工作代码

#include<iostream>
#include<vector>
using namespace std;
template <typename P, typename V>
class Item
{
public:
    P priority;
    V value;
    Item(P priority, V value): priority(priority), value(value) {}
};
int main()
{
    Item<int, string> Item1(18, "string 1");
    Item<int, string> Item2(16, "string 2");
    Item<int, string> Item3(12, "string 3");
    Item<int, string> ItemL[3] = {Item1, Item2, Item3}; 
    vector<Item<int, string> > Items(ItemL, ItemL+3);
}

你有几个问题:

  1. Item&lt;int, string&gt; Item[3] = {Item1, Item2, Item3} 行后缺少分号
  2. Item&lt;int, string&gt; Item[3] 行中你的类名Item 和名为Item 的项目数组不明确。所以重命名为别的名字,我重命名为ItemL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    相关资源
    最近更新 更多