栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++:运算符重载示例

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++:运算符重载示例

#pragma once
//利用成员运算符重载实现两个复数的加法
class Complex
{
public:
	Complex();
	Complex(double a, double b);
	Complex operator +(Complex &rc);		//重载运算符
	void Display();
	~Complex();
private:
	double m_real;		//实部
	double m_imag;      //虚部
};

#include "stdafx.h"
#include "Complex.h"
#include 
using namespace std;

Complex::Complex()
{
	m_real = 0;
	m_imag = 0;
}
Complex::Complex(double a, double b)
{
	m_real = a;
	m_imag = b;
}
Complex Complex::operator +(Complex &rc)		//重载运算符
{
	Complex c;
	c.m_real = m_real + rc.m_real;		//rc为右操作数
	c.m_imag = m_imag + rc.m_imag;
	return c;
}
void Complex::Display()
{
	cout << "(" << m_real << "," << m_imag << "i)" << endl;

}

Complex::~Complex()
{
}
// ComplexExample.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include "Complex.h"
#include 
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	Complex c1(1, 2), c2(3, 4), c3;
	c3 = c1 + c2;		//等价于c3 = c1.operator +(c2)
	cout << "c1 =";  c1.Display() ;
	cout << "c2 =";  c2.Display();
	cout << "c3 =";  c3.Display();
	getchar();
	return 0;
}

运行结果:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857209.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号