我得到一个编译错误与下面的代码:C++默认构造
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复杂&,它的工作原理。 我在想,将使用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();
}
你怎么调用构造函数? – Argote 2011-01-31 21:29:18
如果它和`const`一起工作,那么你为什么不坚持? – 2011-01-31 21:29:54
Microsoft的编译器不报告这些错误。它按照您的预期执行,即。它将Complex a = 2视为Complex a(2,0)。其他编译器可以将其视为Complex a = temp,其中temp是初始化的。在这种情况下,复制构造函数成为问题。 const修饰符的缺失意味着temp的只读属性不能保证。 – 2011-01-31 21:44:41