C++ 重新定义的复制构造函数无法执行
我在下面声明了一个类是头文件:C++ 重新定义的复制构造函数无法执行,c++,c++11,compiler-errors,syntax-error,C++,C++11,Compiler Errors,Syntax Error,我在下面声明了一个类是头文件: class Complex { private: int real; int imaginary; public: Complex(); // no arg contructor Complex(int,int); // 2 - args constructor Complex(const Complex& temp); // copy constructor }; 不,我正在再次尝试声明复制构造函数,我知道
class Complex
{
private:
int real;
int imaginary;
public:
Complex(); // no arg contructor
Complex(int,int); // 2 - args constructor
Complex(const Complex& temp); // copy constructor
};
不,我正在再次尝试声明复制构造函数,我知道它可以工作,但希望有更多的功能,但当我在实现文件中包含它的代码时,它不工作
Compelx::Complex(const Complex& temp) // copy constructor
{
real = 2*temp.real;
imaginary =2*temp.imaginary;
}
在main()
中,我有以下代码
Complex a,b;
a.setReal(10);
cout<<a.getReal()<<endl;
b=a; // problem is here, copy constructor(that is redefined one) is not being executed.
b.print();
复合物a,b;
a、 setReal(10);
coutComplex.cpp(22):错误C2143:语法错误
:缺少“;”“{”1>Complex.cpp(22)之前:错误C2447:“{”:缺少
函数标题(旧式正式列表?)1>main.cpp 1>生成
代码。。。
======生成:0成功,1失败,0最新,0跳过==========
看起来像是拼写错误,请尝试替换
Compelx::Complex(const Complex& temp) // copy constructor
与
请参见差异。此语句是一个赋值,您尚未提供复制赋值运算符的实现:Complex&operator=(const Complex&)
。使用,您可以重用复制构造函数来实现该运算符。您使用的是复制赋值运算符,而不是复制构造函数。复制构造函数调用如下所示:
Complex b(a);
您所呼叫的具有以下签名:
Complex& operator=(const Complex& rhs);
您知道C++有.<代码> b=a;< /COD>不调用复制构造函数,但操作符=,在构造对象时预期。我不知道,但这不是重点,我被要求去做它。JoachimPileborg@JoachimPileborg:不包含整数部分。顺便说一句,复制构造函数已损坏。某些情况允许优化程序跳过一个复制,而此copy构造函数将导致奇怪的结果,因为跳过它会留下与调用它时不同的对象。复制构造函数也可能看起来像Complex b=a;
Complex b(a);
Complex& operator=(const Complex& rhs);