#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 *轉換?
[鏈接隱式轉換運算符]的可能重複(http://stackoverflow.com/questions/8610511/chaining-implicit-conversion-operators) –
答案已經給出。只需加上: 'HasPtrValue(const char * s):ps(new std :: string(s)){std :: cout <<「string/constcharptr」<< std :: endl; }' –