Complex 复数类
显示地写出构造、清理、拷贝和移动。
Complex类
class Complex
{
private:
double real = 3; //复数的实部
double imag = 4; //复数的虚部
public:
Complex(); /*无参构造*/
Complex(double a, double b); /*有参构造*/
Complex(Complex& Z); /*拷贝构造*/
Complex(Complex&& Z); /*移动构造*/
~Complex(); /*析构函数*/
Complex& operator = (Complex& Z); /*拷贝赋值*/
Complex& operator = (Complex&& Z); /*移动赋值*/
void Complex_Printf(void);
};
Complex类实现
/*无参构造*/
Complex::Complex()
{
cout << "无参构造:";
}
/*有参构造*/
Complex::Complex(double a, double b) :real(a), imag(b)
{
cout << "有参构造:";
}
/*拷贝构造*/
Complex::Complex(Complex& Z) :real(Z.real), imag(Z.imag)
{
cout << "复制构造:";
}
/*移动构造*/
Complex::Complex(Complex&& Z) :real(Z.real), imag(Z.imag)
{
cout << "移动构造:";
}
/*析构函数*/
Complex::~Complex()
{
cout << "析构函数" << endl;
}
/*拷贝赋值*/
Complex& Complex::operator = (Complex& Z)
{
real = Z.real;
imag = Z.imag;
cout << "拷贝赋值:";
return *this;
}
/*移动赋值*/
Complex& Complex::operator = (Complex&& Z)
{
real = Z.real;
imag = Z.imag;
cout << "移动赋值:";
return *this;
}
void Complex::Complex_Printf(void)
{
cout << real << " + " << imag << "i" << endl;
}
测试:
#include "Complex.h"
#include <iostream>
using namespace std;
Complex GetComplex()
{
// Complex Z1{ 2, 5 };
Complex Z2{ 4, 8 };
return Z2;
}
int main(void)
{
Complex Z1;/*无参构造*/
Z1.Complex_Printf();
Complex Z2 = { 2, 5 };/*有参构造*/
Z2.Complex_Printf();
Complex Z3 = { Z1 };/*拷贝构造*/
Z3.Complex_Printf();
Z3 = Z2; /*拷贝赋值*/
Z3.Complex_Printf();
Complex Z4 = move(Z1); /*移动构造*/
Z4.Complex_Printf();
Z4 = GetComplex(); /*移动赋值*/
Z4.Complex_Printf();
/*std:move() 强制变成右值*/
}