2017-06-01 152 views
-3

我寫了一個抽象類foo,並且bar類從foo繼承。map <string,pair <string,foo * >>和map <string,pair <string,foo&>>有什麼區別?

我想創建一個地圖容器,它是map<string, pair<string, foo&>>,但我無法成功編譯。編譯器告訴我

「std::pair<std::string,foo &>::pair」: not appropriate default constructor 

這裏是代碼:

#include <iostream> 
#include <string> 
#include <windows.h> 
#include <map> 
#include <utility> 

using namespace std; 

class foo 
{ 
public: 
    virtual void t() = 0; 
}; 

class bar :public foo 
{ 
public: 
    void t() 
    { 
     cout << "bar" << endl; 
    } 
}; 

int main() 
{ 
    bar b; 
    //wrong 
    //map<string, pair<string, foo&>> t; 
    //pair<string, foo&> p("b", b); 
    //t["t"] = p; 

    //right 
    map<string, pair<string, foo*>> t; 
    pair<string, foo*> p("b", &b); 
    t["t"] = p; 
    p.second->t(); 
} 

我想知道map<string, pair<string, foo*>>map<string, pair<string, foo&>>之間的差異。

+5

你知道指針和引用之間有什麼不同嗎? – NathanOliver

+2

https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in –

+0

@FrançoisAndrieux您能否詳細解釋一下原因? – lens

回答

1

第一個示例(您標記爲「錯誤」)的問題是行t[" t"] = p;。如果你看一下文檔std::map::operator[]你會發現下面的一段話:

  • VALUE_TYPE必須是從的std :: piecewise_construct,性病:: forward_as_tuple(鍵),性病::元組<>()EmplaceConstructible。

這意味着你的mapped_type(在這種情況下,foo&)必須是缺省構造的。但是,引用必須是總是引用一個現有的對象,它們不能被默認構造。使用指針的例子很好,因爲指針沒有這個限制。

您可以使用引用作爲mapped_type,但您必須避免operator[]。例如,您可以找到一個帶有std::map::find的元素或使用std::map::emplace插入一個元素。下面的例子編譯得很好:

#include <string> 
#include <map> 
#include <utility> 

using namespace std; 

struct foo {}; 

int main() 
{ 
    foo b; 
    //wrong 
    map<string, pair<string, foo&>> t; 
    pair<string, foo&> p("b", b); 
    t.emplace("t", p); 
} 
相關問題