2015-08-28 200 views
1
#include <string> 
#include <iostream> 
#include <vector> 

class HasPtrValue { 
public: 
    HasPtrValue(const HasPtrValue& h): ps(new std::string(*h.ps)) { std::cout << "copy" << std::endl;} 
    HasPtrValue(const std::string &s = std::string()): ps(new std::string(s)) { std::cout << "string/default" << std::endl;} 
    ~HasPtrValue() { delete ps; } 
private: 
    std::string *ps; 
}; 

using namespace std; 

int main(){ 
    string s = "stackoverflow"; 
    vector<HasPtrValue> a(5, s); 
} 

上述代碼功能匹配編譯好輸出:在矢量構造

string/default 
copy 
copy 
copy 
copy 
copy 

這表明對我的向量第一直接初始化使用字符串對象的臨時HasPtrValue對象(做HasPtrValue(S))和然後從這個臨時文件中複製構建5個元素。怎麼來的,那麼,下面的代碼無法編譯:

int main(){ 
    vector<HasPtrValue> a(5, "stackoverflow"); 
} 

如果它是直接初始化的HasPtrValue(做HasPtrValue(「計算器」)),那麼將在常量字符串&構造佔用沒有問題創建臨時角色。我得到錯誤;

error: no matching function for call to 'std::vector<HasPtrValue>::vector(int, const char [14])'| 

我想我有一個使用int構造和轉換從雙簡單的類嘗試:

class A{ 
public: 
    A(const int& a): x(a) { } 
    int x = 2; 
}; 

int main(){ 
    vector<A> a(5, 5.5); 

} 

除本編譯罰款。向量實現的哪些部分阻止在構造函數中使用const char *轉換?

+0

[鏈接隱式轉換運算符]的可能重複(http://stackoverflow.com/questions/8610511/chaining-implicit-conversion-operators) –

+0

答案已經給出。只需加上: 'HasPtrValue(const char * s):ps(new std :: string(s)){std :: cout <<「string/constcharptr」<< std :: endl; }' –

回答

3

,因爲它需要兩個用戶定義的轉換,const char* - >std::string,然後std::string - >HasPtrValue,但只有一次用戶定義的隱式轉換的中的隱式轉換序列允許的。

13.3.3.1.2 $ 1用戶定義的轉換序列[over.ics.user]

甲用戶定義的轉換序列由初始標準 轉換序列和其後的用戶自定義的轉換的(12.3) 後跟第二個標準轉換序列。

注意這裏只有一個級別的用戶定義的隱式轉換是合法的。對於你的情況,這必須通過明確的轉換來處理;所以,你可以:

vector<HasPtrValue> a(5, std::string("stackoverflow")); 
+2

或者自C++ 14''stackoverflow「s'。 – Jarod42

0
int main(){ 
    vector<HasPtrValue> a(5, string("stackoverflow")); 
} 

你的構造函數需要std::string和 「計算器」 是char陣列。 或者,您可以定義接受char[]的其他構造函數。