学习笔记:重载运算符

参考书目:C/C++规范设计简明教程,P326

目的:学习运算符的重载

第一步:建立工程,添加Complex类

头文件Complex.h如下:

#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
class Complex
{
private:
	int real;	//实部
	int image;	//虚部
public:
	Complex();
	Complex(int r, int i);
	Complex operator+ (Complex & c2);		//运算符重载
	//Complex operator+ (Complex &c1, Complex &c2);		//运算符参数太多,不能这么使用
	void display();
};

源文件Complex.cpp如下:

#include "Complex.h"
Complex::Complex()
{
	real = 0;
	image = 0;
}
Complex::Complex(int r, int i)
{
	real = r;
	image = i;
}
Complex Complex::operator+ (Complex & c2)		//运算符重载
{
	Complex sum;
	sum.real = this->real + c2.real;	//实部相加
	sum.image = this->image + c2.image;	//虚部相加
	return sum;
}

//以下方式+的运算符太多,不能这么使用
//Complex Complex:: operator+ (Complex &c1, Complex&c2)		//运算符重载
//{
//	Complex sum;
//	sum.real = c1.real + c2.real;	//实部相加
//	sum.image = c1.image + c2.image;	//虚部相加
//	return sum;
//}

void Complex::display()
{
	cout <<"结果是:" << real << "+" << image << "i" << endl;
}

第二步:主文件如下

//测试重载运算符

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "Complex.h"
using namespace std;
int main()
{
	cout << "Hello World!\n";

	Complex c1(3, 4), c2(5, 6);
	Complex c3;
	c3 = c1 + c2;	//等价于c3 = c1.add(c2)
	c3.display();


	getchar();
}

运行结果如下:

发布了34 篇原创文章 · 获赞 1 · 访问量 735

猜你喜欢

转载自blog.csdn.net/qq_41708281/article/details/104167260