C++ C++;传递给const引用的文本将导致自动构造
如果我调用“func(const generic&ref)”并以整数作为参数(而不是“generic”对象),则将调用构造函数generic(int\u a)来创建新对象C++ C++;传递给const引用的文本将导致自动构造,c++,c++11,reference,constants,literals,C++,C++11,Reference,Constants,Literals,如果我调用“func(const generic&ref)”并以整数作为参数(而不是“generic”对象),则将调用构造函数generic(int\u a)来创建新对象 class generic { public: int a; generic() {} generic(int _a) : a(_a) { std::cout << "int constructor was called!"; } generic(const
class generic {
public:
int a;
generic() {}
generic(int _a) : a(_a) {
std::cout << "int constructor was called!";
}
generic(const generic& in) : a(in.a) {
std::cout << "copy constructor was called!";
}
};
void func(const generic& ref) {
std::cout << ref.a;
}
int main() {
generic g(2);
func(g); // this is good.
func(generic(4)); // this is good.
func(8); // this is good...... ?
return 0;
}
单独传递整数有什么好处(除了节省时间之外)
这种建筑有名字吗?程序员不应该在传递参数之前显式构造对象吗
如果不希望发生这种情况,可以将添加到构造函数中:
explicit generic(int _a) : a(_a)
{
std::cout << "int constructor was called!";
}
显式泛型(int\u a):a(\u a)
{
这种行为是过程的一部分,特别是
调用func()
时,编译器会构造一个候选列表。只有一个候选对象,func(const generic&ref)
,因此编译器会尝试找出如何进行调用
它看到没有func(int)
已定义,因此它尝试查找从int
到generic
的转换路径。由于有一个generic
的构造函数接受int
,并且没有其他转换允许执行相同的调用,因此编译器采用构造+调用路径
编译器按优先级从高到低的顺序检查三件事:
- 精确匹配
- 晋升
- 转化
这意味着签名的精确匹配胜过需要升级的匹配,而需要升级的匹配胜过需要转换的匹配
有关如何应用隐式转换的信息,请参阅上面链接的文档的“隐式转换序列的排序”。您有一个构造函数,它接受int
,因此编译器将使用它来生成泛型
。如果您不想让它使用该构造函数,请使用explicit
关键字。
explicit generic(int _a) : a(_a)
{
std::cout << "int constructor was called!";
}