#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; }' –