转换构造函数:如何解释在c ++中给出不同参数的函数

Han*_*otc 0 c++

我想了解以下代码.我的问题是函数f().我不明白为什么当我们传递一个整数参数时,我们没有编译错误.

该函数 void f(const A &a1, const A &a2 = A())有两个const参数,它们在我们称为f(3)的main函数中作为对A类的引用传递.我真的不明白究竟发生了什么.

我找不到问题的正确标题.对于这里发生的事情,是否有技术词汇?


#include <iostream>

class A
{
public:
    A(int n = 0)
        : m_n(n)
    {
        std::cout << 'd';
    }

    A(const A& a)
        : m_n(a.m_n)
    {
        std::cout << 'c';
    }

private:
    int m_n;
};

void f(const A &a1, const A &a2 = A())
{
}

int main()
{
    A a(2), b;
    const A c(a), &d = c, e = b;
    b = d;
    A *p = new A(c), *q = &a;
    static_cast<void>(q);
    delete p;
    f(3);
    std::cout << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ght 5

在c ++中,只有一个参数的构造函数称为转换构造函数.函数没有抱怨的原因是因为传递值所需的复制操作a1A(int n = 0)隐式使用.

通过标记来阻止这种情况发生 explicit

explicit A(int n = 0)
Run Code Online (Sandbox Code Playgroud)

作为旁注; 通常认为总是将单个参数构造函数标记为显式是好的做法,除非你真的想要这种行为(为什么?!)

  • [*"转换构造函数"*](http://en.cppreference.com/w/cpp/language/converting_constructor)而不是"隐式复制构造函数" (3认同)