我不明白这种超负荷是怎么解决的;作品“; 我有一个C++类,其中构造函数对于不同的数据类型重载。一个说明问题的简化示例是: #include <iostream> #include <vector> #include <string> class c { public: c(const std::string& n, int v) : name(n), int_value(v) { std::cout << "Running <int> constructor" << std::endl; } c(const std::string& n, double v, const std::vector<double>& extra_args) : name(n), double_value(v) args(extra_args) { std::cout << "Running <double> constructor" << std::endl; } private: std::string name; int int_value; double double_value; std::vector<double> args; }; int main(int argc, char **argv) { c i("name", int()); // This line should in my opinion not compile at all; but // it ends up calling the (std::string&, int) constructor. c d("name", double()); }

我不明白这种超负荷是怎么解决的;作品“; 我有一个C++类,其中构造函数对于不同的数据类型重载。一个说明问题的简化示例是: #include <iostream> #include <vector> #include <string> class c { public: c(const std::string& n, int v) : name(n), int_value(v) { std::cout << "Running <int> constructor" << std::endl; } c(const std::string& n, double v, const std::vector<double>& extra_args) : name(n), double_value(v) args(extra_args) { std::cout << "Running <double> constructor" << std::endl; } private: std::string name; int int_value; double double_value; std::vector<double> args; }; int main(int argc, char **argv) { c i("name", int()); // This line should in my opinion not compile at all; but // it ends up calling the (std::string&, int) constructor. c d("name", double()); },c++,C++,然而我根本不希望它编译。对于重载解析,编译器首先必须检查重载是否可以接受调用时提供的参数数量。这是一个确定哪些函数适用于此函数调用表达式的过程 第一个重载只能接受两个,而第二个重载只能接受三个。在这两种情况下,都会立即取消第二次过载的资格。因此,重载集包含两个调用的单个成员 现在,编译器必须检查它是否能够形成从每个参数到每个参数类型的转换序列。“name”文本通过构造函数转换为std::string,而double则隐式转换为int。因此,对于集合中唯一的重载,形成转换序列是成功的。因此,它被调

然而我根本不希望它编译。

对于重载解析,编译器首先必须检查重载是否可以接受调用时提供的参数数量。这是一个确定哪些函数适用于此函数调用表达式的过程

第一个重载只能接受两个,而第二个重载只能接受三个。在这两种情况下,都会立即取消第二次过载的资格。因此,重载集包含两个调用的单个成员


现在,编译器必须检查它是否能够形成从每个参数到每个参数类型的转换序列。
“name”
文本通过构造函数转换为
std::string
,而
double
则隐式转换为
int
。因此,对于集合中唯一的重载,形成转换序列是成功的。因此,它被调用。

double
可以隐式转换为
int
,这允许调用第一个构造函数

如果要确保传递
双精度
时不会有人调用它,可以显式删除它

c类{
公众:
c(const std::string&n,双d)=删除;
.
.
.
};
int main(){
ca{“a”,1);//好,调用c(const std::string&n,int i);
//c b{“b”,1.0);编译错误!尝试调用已删除的函数
//c(常量标准::字符串和n,双d)
cb{“c”,static_cast(1.0)};//好,调用c(const std::string&n,int i);
}

我想编译器应该发出警告,它正在将double转换为int。显然,这是一个更好的匹配,其他重载需要更多的参数,double可以透明地转换为int。作为补充说明,2019年,您不会通过const引用传递参数,而只是复制参数,而是通过值传递参数并构造成员with
std::move
。可以使用
std::enable_if
std::is_integral
和int重载来防止从
double
@user422005进行隐式转换。如果要避免隐式转换并使其无法编译,可以将构造函数声明为
explicit
。我尝试使用
explicit-但后来它编译为“不应该”。@user422005啊,我刚刚意识到它不起作用。我认为
显式
是为了避免类实例隐式转换,而不是参数。我的不好。谢谢-
=delete;
帮助我得到了我想要的编译器错误。
Running <int> constructor
Running <int> constructor