//拷贝构造函数的三种应用:
//(1)函数值的整体拷贝;(2)函数参数调用;(3)返回值
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
class complex
{
private:
double real;
double imag;
public:
complex(double r=0.0,double i=0.0)
{
real=r;
imag=i;
}
//函数的引用,相当于赋别名
complex(complex &c)
{
real=c.real;imag=c.imag;
}
double realcomplex()
{
return real;
}
double imagcomplex()
{
return imag;
}
double abscomplex()
{
double t;
t=real*real+imag*imag;
return sqrt(t);
}
};
void display(complex p)//普通函数调用,但参数是一个类类型的参数
{
cout<<"real of p:"<<p.realcomplex()<<"\n"<<"imag of p:"<<p.imagcomplex()<<"\n"
<<"abs of p:"<<p.abscomplex()<<endl;
}
complex fun() //定义的函数返回值类型为类类型
{
complex m(2.1,3.2);
return m;
}
void main()
{
complex a(1.2,3.4);//第一种情况,对象拷贝,在同是类类型的基础上
complex b(a);
cout<<"real of a:"<<a.realcomplex()<<"\n"<<"imag of a:"<<a.imagcomplex()<<"\n"
<<"abs of a:"<<a.abscomplex()<<endl;
cout<<"real of b:"<<b.realcomplex()<<"\n"<<"imag of b:"<<b.imagcomplex()<<"\n"
<<"abs of b:"<<b.abscomplex()<<endl;
complex c(2.4,4.5);//第二种情况,类类型参数传递
display(c);
complex n;//第三种情况,返回值为一个类类型对象
n=fun();
cout<<"real of n:"<<n.realcomplex()<<"\n"<<"imag of n:"<<n.imagcomplex()<<"\n"
<<"abs of n:"<<n.abscomplex()<<endl;
system("pause");
}
拷贝构造函数的三种应用
最新推荐文章于 2021-07-24 20:03:23 发布