C++中的多个构造函数

Inc*_*ion -5 c++ constructor

问题是关于多个让我困惑的构造函数.

#include "complex.h"
#include <iostream>

using namespace std;

Complex::Complex(double realPart, double imPart)
    : m_R(realPart), m_I(imPart)
{
    cout << "complex(" << m_R << "," << m_I << ")" << endl;
}

Complex::Complex(double realPart)
{
    Complex(realPart, 0);
}

Complex::Complex() : m_R(0.0), m_I(0.0)
{
}

int main() {
    Complex C1;
    Complex C2(3.14);
    Complex C3(6.2, 10.23);
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释编译器如何知道使用哪三个构造函数定义?Primer来自本书,第58页.

小智 9

边注

如果要使用C++ 11委托构造函数,则应编写:

Complex::Complex(double realPart) 
:    Complex(realPart, 0)
{}
Run Code Online (Sandbox Code Playgroud)

代替

Complex::Complex(double realPart) {
    Complex(realPart, 0);
    }
Run Code Online (Sandbox Code Playgroud)

这会Complex在构造函数体内创建一个临时未使用的.


Mar*_*ica 5

这取决于提供给构造函数的参数的数量和类型。因此

std::Complex first(1, 2.0); // Use first constructor
std::Complex second(5.0);   // Use second constructor
std::Complex third;         // Use third constructor with no arguments.
Run Code Online (Sandbox Code Playgroud)