向量构造函数中的函数匹配
Function matching in vector constructors
#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(,然后从这个临时对象复制构造 5 个元素。那么,为什么下面的代码不能编译:
int main(){
vector<HasPtrValue> a(5, "stackoverflow");
}
如果它直接初始化 HasPtrValue(执行 HasPtrValue("stackoverflow"((,那么 const string&constructor 承担创建临时角色就不会有问题。我收到错误;
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* 转换?
因为它需要两个用户定义的转换,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"));
int main(){
vector<HasPtrValue> a(5, string("stackoverflow"));
}
您的构造函数需要std::string
并且"stackoverflow"char
数组。或者,您可以定义接受char[]
的其他构造函数。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- makefile对我的名称空间对象/函数/构造函数的不确定引用
- 没有可调用的匹配函数(构造函数),候选函数不同于对给定类型的引用
- C++库制作,隐藏在标头中没有友元的析构函数/构造函数
- 从另一个成员函数/构造函数调用C++构造函数是否执行初始值设定项列表
- 在另一个函数/构造函数 [C++] 中初始化后使变量只读
- std::调用函数时找不到函数构造函数
- 显式调用基类析构函数/构造函数合法吗
- 函数构造函数和nullptr
- 用委托构造函数构造函数
- 虚函数构造函数和调用虚函数时会发生什么
- 一些Qt函数/构造函数参数的内存管理
- 使用for_each或std::transform时,c++函函数构造函数是如何被调用的?
- std函数构造函数初始化