<C/C++基础> 设计一个复数类(拷贝函数的使用)

一,设计要求

要求:复数 由两个实数组成。因此该类至少应包含两个“私有”成员变量,
还应具有如下成员函数:
1)多种构造函数;
2)析构函数;
3)取实部和虚部;
4)求模;
5)求主幅角;
6)单目运算:++等;
7)双目运算:重构运算符操作+ , - , x , /等
8)混合运算


二,代码实现

关于拷贝函数为什么一定要用引用,拷贝构造函数的类型为什么必须使用引用类型,该文章讲得很清晰!文末保留了该文章。

1,Complex.h代码如下(友元实现的重载运算符,其实也可以用成员函数实现)

#include <iostream>  
#include "math.h"
using namespace std; 
class Complex 
{ 
public: 
	Complex( )
	{real=0;imag=0;} 
	Complex(double r)
	{real=r;imag=0;}
	Complex(double r,double i)
	{real=r;imag=i;}  
	Complex(const Complex& c)//复制构造函数(一定要用引用)
	{real=c.real;imag=c.imag;} 
	~Complex(){}

	double getReal()
	{
		return this->real;
	}
	double getImag()
	{
		return this->imag;
	}
	//使用友元来重载运算符(注意,这些函数都不属于这个类,他没有this指针)

	//输入输出运算符重载  
	friend istream& operator>>(istream &in,Complex c); 
	friend ostream& operator<<(ostream &out,Complex c); 
	//双目运算:加减乘除运算符重载  
	friend Complex operator+(Complex c1,Complex c2); 
	friend Complex operator-(Complex c1,Complex c2); 
	friend Complex operator*(Complex c1,Complex c2); 
	friend Complex operator/(Complex c1,Complex c2); 
	
	//单目运算:自增
	friend Complex operator++(Complex c);//前置
	friend Complex operator++(Complex c,int);//hou置

	//双目运算:混合运算
	friend Complex operator+=(Complex c,double d);
	friend Complex operator+(Complex c1,double d);
	friend Complex operator+(double d,Complex c1);

	//比较运算
	friend bool operator==(Complex c1,Complex c2);
	friend bool operator!=(Complex c1,Complex c2);
	//成员函数
	Complex abs();//求绝对值
	double mod();
	double arg();
private: 
	double real; 
	double imag; 
}; 

//输入运算符重载  
istream & operator>>(istream& in,Complex c) 
{ 
	in>>c.real>>c.imag; 
	return in; 
} 
//输出运算符重载  
ostream & operator<<(ostream &out,Complex c) 
{ 
	if (c.getImag()>=0)
	{
		out<<"("<<c.real<<"+"<<c.imag<<"i)"<<"    "; 
	}
	else
	{
		out<<"("<<c.real<<c.imag<<"i)"<<"    ";
	}
	return out; 
} 

Complex operator+(Complex c1,double d) 
{ 
	Complex c; 
	c.real=c1.real+d;
	return c; 
}

Complex operator+(double d,Complex c1) 
{ 
	Complex c; 
	c.real=c1.real+d;
	return c; 
}

bool operator==(Complex c1,Complex c2) 
{ 
	if (c1.imag==c2.imag&&c1.real==c2.real)
	{
		return true;
	}else
	{
		return false;
	}
} 

bool operator!=(Complex c1,Complex c2) 
{ 
	if (c1.imag!=c2.imag||c1.real!=c2.real)
	{
		return true;
	}else
	{
		return false;
	}
} 
//加减乘除运算符重载 
Complex operator+(Complex c1,Complex c2) 
{ 
	Complex c; 
	c.real=c1.real+c2.real; 
	c.imag=c1.imag+c2.imag; 
	return c; 
} 

Complex operator-(Complex c1,Complex c2) 
{ 
	Complex c; 
	c.real=c1.real-c2.real; 
	c.imag=c1.imag-c2.imag; 
	return c; 
} 

Complex operator*(Complex c1,Complex c2) 
{ 
	Complex c; 
	c.real=c1.real*c2.real-c1.imag*c2.imag; 
	c.imag=c1.imag*c2.real+c1.real*c2.imag; 
	return c; 
} 

Complex operator/(Complex c1,Complex c2) 
{ 
	Complex c; 
	c.real=(c1.real/c2.real+c1.imag/c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); 
	c.imag=(c1.imag/c2.real-c1.real/c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); 
	return c; 
} 

Complex operator++(Complex c) 
{ 
	
	++c.real;
	++c.imag;
	return c; 
}

Complex operator++(Complex c,int) 
{ 

	++c.real;
	++c.imag;
	return c; 
}

Complex  Complex::abs()
{
	Complex temp;
	temp.real=(this->real>=0)?this->real:(-this->real);
	temp.imag=(this->imag>=0)?this->imag:(-this->imag);
	return temp;
}

double  Complex::mod()
{
	double temp=0.0;
	temp=pow(this->real,2.0)+pow(this->imag,2.0);
	temp=sqrt(temp);
	return temp;
}

double Complex::arg()
{
	double temp=0.0;
	temp=atan(imag/real);
	temp=temp*57.296;
	return temp;
}


(2)主测试程序:

// ConsoleAppComplex.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "ComplexNum.h"

int _tmain(int argc, _TCHAR* argv[])
{
	system("color 0A");
	cout<<"/******************************华丽的分割线*****************************/"<<endl;
	Complex ans; 
	Complex c1(-2.0),c2(1,-0.5),c3=3,c4(c2);
	cout<<"您设定的四个复数"<<"c1:"<<c1<<" c2:"<<c2<<" c3:"<<c3<<" c4:"<<c4<<endl;

	ans=c1*c2;
	cout<<"c1*c2="<<ans<<endl; 

	ans=c1/c2; 
	cout<<"c1/c2="<<ans<<endl; 

	ans=c1+c2;
	cout<<"c1+c2="<<ans<<endl; 

	ans=c1-c2; 
	cout<<"c1-c2="<<ans<<endl; 
	ans=ans.abs();
	cout<<"c1-c2的结果绝对值后:"<<ans<<endl; 
	cout<<endl<<"/******************************华丽的分割线*****************************/"<<endl;

	if (c1==c3)
	{
		cout<<"复数c1与c3相等!"<<endl; 
	}else 
	{
		cout<<"复数c1与c3不相等!"<<endl; 
	}
	if (c4==c2)
	{
		cout<<"复数c2与c4相等!"<<endl; 
	}else 
	{
		cout<<"复数c2与c4不相等!"<<endl; 
	}



	cout<<endl<<"/******************************华丽的分割线*****************************/"<<endl;
	double ans1=0.0;
	ans1=ans.mod();
	cout<<"c1-c2的结果取模后:"<<ans1<<endl;
	Complex ans3;
	ans3=c1+ans1;
	cout<<"c1+ans1(模值)="<<ans3<<endl;

	ans3=ans1+c2;
	cout<<"ans1(模值)+c2="<<ans3<<endl;

	double ans2=0.0;
	ans2=ans.arg();
	cout<<"c1-c2的结果主幅角:"<<ans2<<"度"<<endl;

	cout<<"单目运算:第一个复数前置自增"<<++c1<<endl;
	cout<<"单目运算:第二个复数后置自增"<<c2++<<endl;
	cout<<endl<<"/******************************华丽的分割线*****************************/"<<endl;
	cout<<"请输入第一个复数的实部与虚部"<<endl;
	cin>>c1; 
	cout<<"请输入第二个复数的实部与虚部"<<endl;
	cin>>c2; 
	cout<<"您输入的两个复数为"<<c1<<"    "<<c2<<endl; 

	ans=c1+c2; 
	cout<<"c1+c2="<<ans<<endl; 

	ans=c1-c2; 
	cout<<"c1-c2="<<ans<<endl; 
	
	system("pause");
	return 0; 
}





(3)测试结果:






保留文:C++拷贝构造函数详解

一. 什么是拷贝构造函数

首先对于普通类型的对象来说,它们之间的复制是很简单的,例如:

[c-sharp]  view plain  copy
  1. int a = 100;  
  2. int b = a;   

而类对象与普通对象不同,类对象内部结构一般较为复杂,存在各种成员变量。
下面看一个类对象拷贝的简单例子。

[c-sharp]  view plain  copy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class CExample {  
  5. private:  
  6.      int a;  
  7. public:  
  8.       //构造函数  
  9.      CExample(int b)  
  10.      { a = b;}  
  11.   
  12.       //一般函数  
  13.      void Show ()  
  14.      {  
  15.         cout<<a<<endl;  
  16.       }  
  17. };  
  18.   
  19. int main()  
  20. {  
  21.      CExample A(100);  
  22.      CExample B = A; //注意这里的对象初始化要调用拷贝构造函数,而非赋值  
  23.       B.Show ();  
  24.      return 0;  
  25. }  

运行程序,屏幕输出100。从以上代码的运行结果可以看出,系统为对象 B 分配了内存并完成了与对象 A 的复制过程。就类对象而言,相同类型的类对象是通过拷贝构造函数来完成整个复制过程的

下面举例说明拷贝构造函数的工作过程。

[c-sharp]  view plain  copy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class CExample {  
  5. private:  
  6.     int a;  
  7. public:  
  8.     //构造函数  
  9.     CExample(int b)  
  10.     { a = b;}  
  11.       
  12.     //拷贝构造函数  
  13.     CExample(const CExample& C)  
  14.     {  
  15.         a = C.a;  
  16.     }  
  17.   
  18.     //一般函数  
  19.     void Show ()  
  20.     {  
  21.         cout<<a<<endl;  
  22.     }  
  23. };  
  24.   
  25. int main()  
  26. {  
  27.     CExample A(100);  
  28.     CExample B = A; // CExample B(A); 也是一样的  
  29.      B.Show ();  
  30.     return 0;  
  31. }   

CExample(const CExample& C) 就是我们自定义的拷贝构造函数。可见,拷贝构造函数是一种特殊的 构造函数,函数的名称必须和类名称一致,它必须的一个参数是本类型的一个引用变量


二. 拷贝构造函数的调用时机

在C++中,下面三种对象需要调用拷贝构造函数!
1. 对象以值传递的方式传入函数参数

[c-sharp] view plain copy
  1. class CExample   
  2. {  
  3. private:  
  4.  int a;  
  5.   
  6. public:  
  7.  //构造函数  
  8.  CExample(int b)  
  9.  {   
  10.   a = b;  
  11.   cout<<"creat: "<<a<<endl;  
  12.  }  
  13.   
  14.  //拷贝构造  
  15.  CExample(const CExample& C)  
  16.  {  
  17.   a = C.a;  
  18.   cout<<"copy"<<endl;  
  19.  }  
  20.    
  21.  //析构函数  
  22.  ~CExample()  
  23.  {  
  24.   cout<< "delete: "<<a<<endl;  
  25.  }  
  26.   
  27.      void Show ()  
  28.  {  
  29.          cout<<a<<endl;  
  30.      }  
  31. };  
  32.   
  33. //全局函数,传入的是对象  
  34. void g_Fun(CExample C)  
  35. {  
  36.  cout<<"test"<<endl;  
  37. }  
  38.   
  39. int main()  
  40. {  
  41.  CExample test(1);  
  42.  //传入对象  
  43.  g_Fun(test);  
  44.   
  45.  return 0;  
  46. }  

调用g_Fun()时,会产生以下几个重要步骤:
(1).test对象传入形参时,会先会产生一个临时变量,就叫 C 吧。
(2).然后调用拷贝构造函数把test的值给C。 整个这两个步骤有点像:CExample C(test);
(3).等g_Fun()执行完后, 析构掉 C 对象。

2. 对象以值传递的方式从函数返回

[c-sharp] view plain copy
  1. class CExample   
  2. {  
  3. private:  
  4.  int a;  
  5.   
  6. public:  
  7.  //构造函数  
  8.  CExample(int b)  
  9.  {   
  10.   a = b;  
  11.  }  
  12.   
  13.  //拷贝构造  
  14.  CExample(const CExample& C)  
  15.  {  
  16.   a = C.a;  
  17.   cout<<"copy"<<endl;  
  18.  }  
  19.   
  20.      void Show ()  
  21.      {  
  22.          cout<<a<<endl;  
  23.      }  
  24. };  
  25.   
  26. //全局函数  
  27. CExample g_Fun()  
  28. {  
  29.  CExample temp(0);  
  30.  return temp;  
  31. }  
  32.   
  33. int main()  
  34. {  
  35.  g_Fun();  
  36.  return 0;  
  37. }  

当g_Fun()函数执行到return时,会产生以下几个重要步骤:
(1). 先会产生一个临时变量,就叫XXXX吧。
(2). 然后调用拷贝构造函数把temp的值给XXXX。整个这两个步骤有点像:CExample XXXX(temp);
(3). 在函数执行到最后先析构temp局部变量。
(4). 等g_Fun()执行完后再析构掉XXXX对象。

3. 对象需要通过另外一个对象进行初始化;

[c-sharp] view plain copy
  1. CExample A(100);  
  2. CExample B = A;   
  3. // CExample B(A);   

后两句都会调用拷贝构造函数。


三. 浅拷贝和深拷贝

1. 默认拷贝构造函数

    很多时候在我们都不知道拷贝构造函数的情况下,传递对象给函数参数或者函数返回对象都能很好的进行,这是因为编译器会给我们自动产生一个拷贝构造函数,这就是“默认拷贝构造函数”,这个构造函数很简单,仅仅使用“老对象”的数据成员的值对“新对象”的数据成员一一进行赋值,它一般具有以下形式:

[c-sharp]  view plain  copy
  1. Rect::Rect(const Rect& r)  
  2. {  
  3.     width = r.width;  
  4.     height = r.height;  
  5. }  
 
    当然,以上代码不用我们编写,编译器会为我们自动生成。但是如果认为这样就可以解决对象 的复制问题,那就错了,让我们来考虑以下一段代码:
[c-sharp]  view plain  copy
  1. class Rect  
  2. {  
  3. public:  
  4.     Rect()      // 构造函数,计数器加1  
  5.     {  
  6.         count++;  
  7.     }  
  8.     ~Rect()     // 析构函数,计数器减1  
  9.     {  
  10.         count--;  
  11.     }  
  12.     static int getCount()       // 返回计数器的值  
  13.     {  
  14.         return count;  
  15.     }  
  16. private:  
  17.     int width;  
  18.     int height;  
  19.     static int count;       // 一静态成员做为计数器  
  20. };  
  21.   
  22. int Rect::count = 0;        // 初始化计数器  
  23.   
  24. int main()  
  25. {  
  26.     Rect rect1;  
  27.     cout<<"The count of Rect: "<<Rect::getCount()<<endl;  
  28.   
  29.     Rect rect2(rect1);   // 使用rect1复制rect2,此时应该有两个对象  
  30.      cout<<"The count of Rect: "<<Rect::getCount()<<endl;  
  31.   
  32.     return 0;  
  33. }  

  这段代码对前面的类,加入了一个静态成员,目的是进行计数。在主函数中,首先创建对象rect1,输出此时的对象个数,然后使用rect1复制出对象rect2,再输出此时的对象个数,按照理解,此时应该有两个对象存在,但实际程序运行时,输出的都是1,反应出只有1个对象。此外,在销毁对象时,由于会调用销毁两个对象,类的析构函数会调用两次,此时的计数器将变为负数。

说白了,就是拷贝构造函数没有处理静态数据成员。

出现这些问题最根本就在于在复制对象时,计数器没有递增,我们重新编写拷贝构造函数,如下

[c-sharp]  view plain  copy
  1. class Rect  
  2. {  
  3. public:  
  4.     Rect()      // 构造函数,计数器加1  
  5.     {  
  6.         count++;  
  7.     }  
  8.     Rect(const Rect& r)   // 拷贝构造函数  
  9.     {  
  10.         width = r.width;  
  11.         height = r.height;  
  12.         count++;          // 计数器加1  
  13.     }  
  14.     ~Rect()     // 析构函数,计数器减1  
  15.     {  
  16.         count--;  
  17.     }  
  18.     static int getCount()   // 返回计数器的值  
  19.     {  
  20.         return count;  
  21.     }  
  22. private:  
  23.     int width;  
  24.     int height;  
  25.     static int count;       // 一静态成员做为计数器  
  26. };  

2. 浅拷贝

    所谓浅拷贝,指的是在对象复制时,只对对象中的数据成员进行简单的赋值,默认拷贝构造函数执行的也是浅拷贝。大多情况下“浅拷贝”已经能很好地工作了,但是一旦对象存在了动态成员,那么浅拷贝就会出问题了,让我们考虑如下一段代码:

[c-sharp]  view plain  copy
  1. class Rect  
  2. {  
  3. public:  
  4.     Rect()      // 构造函数,p指向堆中分配的一空间  
  5.     {  
  6.         p = new int(100);  
  7.     }  
  8.     ~Rect()     // 析构函数,释放动态分配的空间  
  9.     {  
  10.         if(p != NULL)  
  11.         {  
  12.             delete p;  
  13.         }  
  14.     }  
  15. private:  
  16.     int width;  
  17.     int height;  
  18.     int *p;     // 一指针成员  
  19. };  
  20.   
  21. int main()  
  22. {  
  23.     Rect rect1;  
  24.     Rect rect2(rect1);   // 复制对象  
  25.     return 0;  
  26. }  

    在这段代码运行结束之前,会出现一个运行错误。原因就在于在进行对象复制时,对于动态分配的内容没有进行正确的操作。我们来分析一下:

    在运行定义rect1对象后,由于在构造函数中有一个动态分配的语句,因此执行后的内存情况大致如下:

 

 

    在使用rect1复制rect2时,由于执行的是浅拷贝,只是将成员的值进行赋值,这时 rect1.p = rect2.p,也即这两个指针指向了堆里的同一个空间,如下图所示:

 

当然,这不是我们所期望的结果,在销毁对象时,两个对象的析构函数将对同一个内存空间释放两,这就是错误出现的原因。我们需要的不是两个p有相同的值,而是两个p指向的空间有相同的值,解决办法就是使用“深拷贝”。


3. 深拷贝

    在“深拷贝”的情况下,对于对象中动态成员,就不能仅仅简单地赋值了,而应该重新动态分配空间,如上面的例子就应该按照如下的方式进行处理:

[c-sharp]  view plain  copy
  1. class Rect  
  2. {  
  3. public:  
  4.     Rect()      // 构造函数,p指向堆中分配的一空间  
  5.     {  
  6.         p = new int(100);  
  7.     }  
  8.     Rect(const Rect& r)  
  9.     {  
  10.         width = r.width;  
  11.         height = r.height;  
  12.         p = new int;    // 为新对象重新动态分配空间  
  13.         *p = *(r.p);  
  14.     }  
  15.     ~Rect()     // 析构函数,释放动态分配的空间  
  16.     {  
  17.         if(p != NULL)  
  18.         {  
  19.             delete p;  
  20.         }  
  21.     }  
  22. private:  
  23.     int width;  
  24.     int height;  
  25.     int *p;     // 一指针成员  
  26. };  

此时,在完成对象的复制后,内存的一个大致情况如下:

 

此时rect1的p和rect2的p各自指向一段内存空间,但它们指向的空间具有相同的内容,这就是所谓的“深拷贝”。


3. 防止默认拷贝发生

    通过对对象复制的分析,我们发现对象的复制大多在进行“值传递”时发生,这里有一个小技巧可以防止按值传递——声明一个私有拷贝构造函数。甚至不必去定义这个拷贝构造函数,这样因为拷贝构造函数是私有的,如果用户试图按值传递或函数返回该类对象,将得到一个编译错误,从而可以避免按值传递或返回对象。

[c-sharp]  view plain  copy
  1. // 防止按值传递  
  2. class CExample   
  3. {  
  4. private:  
  5.     int a;  
  6.   
  7. public:  
  8.     //构造函数  
  9.     CExample(int b)  
  10.     {   
  11.         a = b;  
  12.         cout<<"creat: "<<a<<endl;  
  13.     }  
  14.   
  15. private:  
  16.     //拷贝构造,只是声明  
  17.     CExample(const CExample& C);  
  18.   
  19. public:  
  20.     ~CExample()  
  21.     {  
  22.         cout<< "delete: "<<a<<endl;  
  23.     }  
  24.   
  25.     void Show ()  
  26.     {  
  27.         cout<<a<<endl;  
  28.     }  
  29. };  
  30.   
  31. //全局函数  
  32. void g_Fun(CExample C)  
  33. {  
  34.     cout<<"test"<<endl;  
  35. }  
  36.   
  37. int main()  
  38. {  
  39.     CExample test(1);  
  40.     //g_Fun(test); 按值传递将出错  
  41.       
  42.     return 0;  
  43. }   

四. 拷贝构造函数的几个细节

1. 拷贝构造函数里能调用private成员变量吗?
解答:
这个问题是在网上见的,当时一下子有点晕。其时从名子我们就知道拷贝构造函数其时就是
一个特殊的构造函数,操作的还是自己类的成员变量,所以不受private的限制。


2. 以下函数哪个是拷贝构造函数,为什么?

[c-sharp]  view plain  copy
  1. X::X(const X&);      
  2. X::X(X);      
  3. X::X(X&, int a=1);      
  4. X::X(X&, int a=1, int b=2);  

解答:对于一个类X, 如果一个构造函数的第一个参数是下列之一:
a) X&
b) const X&
c) volatile X&
d) const volatile X&
且没有其他参数或其他参数都有默认值,那么这个函数是拷贝构造函数.

[c-sharp]  view plain  copy
  1. X::X(const X&);  //是拷贝构造函数      
  2. X::X(X&, int=1); //是拷贝构造函数     
  3. X::X(X&, int a=1, int b=2); //当然也是拷贝构造函数  


3. 一个类中可以存在多于一个的拷贝构造函数吗?
解答:
类中可以存在超过一个拷贝构造函数。

[c-sharp]  view plain  copy
  1. class X {   
  2. public:         
  3.   X(const X&);      // const 的拷贝构造  
  4.   X(X&);            // 非const的拷贝构造  
  5. };  

注意,如果一个类中只存在一个参数为 X& 的拷贝构造函数,那么就不能使用const X或volatile X的 对象实行拷贝初始化.

[c-sharp]  view plain  copy
  1. class X {      
  2. public:  
  3.   X();      
  4.   X(X&);  
  5. };      
  6.   
  7. const X cx;      
  8. X x = cx;    // error  

如果一个类中没有定义拷贝构造函数,那么编译器会自动产生一个默认的拷贝构造函数。
这个默认的参数可能为 X::X(const X&)或 X::X(X&),由编译器根据上下文决定选择哪一个。



参考资源:

【1】http://blog.youkuaiyun.com/lwbeyond/article/details/6202256

【2】谷歌大神和《C++程序设计语言》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值