使用以下代码编译时,我遇到了一个编译错误:
main.cpp: In function âint main()â:
main.cpp:38: error: no matching function for call to âComplex::Complex(Complex)â
main.cpp:22: note: candidates are: Complex::Complex(Complex&)
main.cpp:15: note: Complex::Complex(double, double)
但是当我将复制构造函数的参数类型更改为const Complex&时,它可以工作。 我曾经认为默认构造函数将被调用,并使用2个Complex::Complex(2.0, 0.0)创建一个副本,然后使用Complex(2.0. 0)创建一个。这不正确吗?
#include <iostream>
using namespace std;
class Complex {
double re;
double im;
public:
Complex(double re=0, double im=0);
Complex(Complex& c);
~Complex() {};
void print();
};
Complex::Complex(double re, double im)
{
cout << "Constructor called with " << re << " " << im << endl;
this->re = re;
this->im = im;
}
Complex::Complex(Complex &c)
{
cout << "Copy constructor called " << endl;
re = c.re;
im = c.im;
}
void Complex::print()
{
cout << "real = " << re << endl;
cout << "imaginary = " << im << endl;
}
int main()
{
Complex a = 2;
a.print();
Complex b = a;
b.print();
}
const
工作,那你为什么不坚持使用呢? - Björn Pollex