Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;传递给const引用的文本将导致自动构造_C++_C++11_Reference_Constants_Literals - Fatal编程技术网

C++ C++;传递给const引用的文本将导致自动构造

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

如果我调用“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 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!";
}