2015-10-21 58 views
1

我看過相關文章,但仍然無法弄清楚。 在我的.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); 
      ~~~^ 
+0

您已經調用了與您的類「Item」名稱相同的數組「Item」,導致編譯器變得困惑。 –

+2

你也在數組後面缺少一個分號。 – Cornstalks

+0

你的代碼風格很糟糕,如果你使用'Item'作爲一個類,請不要重複使用'Item'作爲其他用途。另外,如果'Foo'是類名,則對象名應該是'foo'。而且,你的'Items'是一個數組,對吧?我們來看看這個數組的聲明。這不是編譯器混淆,這是你的困惑。 – DMaster

回答

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. 分號缺少自動對焦ter Item<int, string> Item[3] = {Item1, Item2, Item3} line
  2. Item<int, string> Item[3] line您的班級名稱Item以及名稱爲Item的數組不明確。所以重命名爲其他名稱,我將其重命名爲ItemL