问题是关于多个让我困惑的构造函数.
#include "complex.h" #includeusing 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); }
有人可以解释编译器如何知道使用哪三个构造函数定义?Primer来自本书,第58页.
边注
如果要使用C++ 11委托构造函数,则应编写:
Complex::Complex(double realPart) : Complex(realPart, 0) {}
代替
Complex::Complex(double realPart) { Complex(realPart, 0); }
这会Complex
在构造函数体内创建一个临时未使用的.