C++学习笔记 第31课 完善复数类

Complex.h
#pragma once

class Complex
{
private:
	double a;
	double b;
public:
	Complex(double a, double b);//这里的a不需要写成a=0.0,会重定义
	int getA();
	int getB();
	Complex operator + (const Complex& p1);
	Complex operator - (const Complex& p1);
	Complex operator * (const Complex& p1);
	Complex operator / (const Complex& p1);

	bool operator  == (const Complex& p1);
	bool operator !=  (const Complex& p1);
	Complex& operator = (const Complex& p1);
};
Complex.cpp
#include "Complex.h"
#include <iostream>

using namespace std;


Complex::Complex(double a = 0.0, double b = 0.0)
{
	this->a = a;
	this->b = b;
}

int Complex::getA()
{
	return this->a;
}

int Complex::getB()
{
	return this->b;
}

Complex Complex::operator + (const Complex& p1)
{
	Complex ret;
	ret.a = this->a + p1.a;
	ret.b = this->b + p1.a;
	return ret;
}
Complex Complex::operator - (const Complex& p1)
{
	Complex ret;
	ret.a = this->a - p1.a;
	ret.b = this->b - p1.a;
	return ret;
}
Complex Complex::operator * (const Complex& p1)
{
	Complex ret;
	ret.a = this->a * p1.a;
	ret.b = this->b * p1.a;
	return ret;
}
Complex Complex::operator / (const Complex& p1)
{
	Complex ret;
	ret.a = this->a / p1.a;
	ret.b = this->b / p1.a;
	return ret;
}

bool Complex::operator  == (const Complex& p1)
{
	if (this->a == p1.a && this->b == p1.b)
	{
		return true;
	}
	else
	{
		return false;
	}
}

bool Complex::operator !=  (const Complex& p1)
{
	if (this->a != p1.a || this->b != p1.b)
	{
		return true;
	}
	else
	{
		return false;
	}
}

Complex& Complex:: operator = (const Complex& p1)
{
	if (this != &p1)
	{
		this->a = p1.a;
		this->b = p1.b;
	}
	return *this;
}
main.cpp
#include "Complex.h"
#include <stdio.h>

int main()
{
	int ret;
	Complex c1(1, 2);
	Complex c2(3, 5);

	Complex c3 = c1 - c2;
	printf("Complex c3 = c1 - c2\nc3.a=%d,c3.b=%d\n", c3.getA(), c3.getB());
	
	ret = c3 == c1;
	printf("ret = %d\n", ret);
	Complex c4 = c1;
	printf("Complex c4:\nc4.a=%d,c4.b=%d\n", c4.getA(), c4.getB());
	return 0;
}

结果展示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值