我已声明下面的一个类是头文件:
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();
复制构造函数未执行,而是出现以下错误:
1&GT; Complex.cpp 1&gt; Complex.cpp(21):错误C2653:'Compelx':不是a 类或命名空间名称1&gt; Complex.cpp(21):错误C2226:语法错误: 意外类型'Complex'1&gt; Complex.cpp(22):错误C2143:语法错误 : 失踪 ';'在'{'1&gt; Complex.cpp(22)之前:错误C2447:'{':缺失 函数头(旧式正式列表?)1&gt; main.cpp 1&gt;发电 码... ==========构建:0成功,1个失败,0个最新,0个跳过==========
答案 0 :(得分:3)
看起来像拼写错误,请尝试替换
Compelx::Complex(const Complex& temp) // copy constructor
与
Complex::Complex(const Complex& temp) // copy constructor
答案 1 :(得分:3)
您使用的是复制赋值运算符,而不是复制构造函数。复制构造函数调用如下所示:
Complex b(a);
你所呼唤的是签名:
Complex& operator=(const Complex& rhs);
答案 2 :(得分:2)
Compelx Complex
看到差异。
答案 3 :(得分:2)
此语句是一项赋值,您尚未为复制赋值运算符提供实现:Complex& operator=(const Complex&)
。使用copy&swap idiom,您可以重复使用copy-constructor来实现该运算符。