C++重载运算符

#pragma once
//重载运算符进行复数运算
#include <iostream>
using std::cout;
using std::endl;//vc++6.0不允许在声明重载运算符之前使用using namespace std;
                //c++的标准标识符都在命名空间std中,或许调用std对重载有影响;
class Complex //定义复数类,使用友元函数重载
{
private :
	double real;
	double image;
public:
	Complex(double  real = 0.0, double image = 0.0)
	{
		this->real = real, this->image = image;
	}
	void display()
	{
		cout << "(" << real << "," << image << ")" << endl;
	}

	//friend Complex operator +(Complex A, Complex B) //重载+为友元类函数,类内定义 类型为Complex
	//{
	//	return Complex(A.real + B.real, A.image + B.image);
	//}
	Complex operator +(Complex B); //此处重载+为成员函数 类型为Complex

	friend Complex operator -(Complex A, Complex B) //重载-为友元类函数;
	{
		return Complex(A.real - B.real, A.image - B.image);
	}

	friend Complex operator -(Complex A);//取负数,类内声明,类外定义
	friend Complex operator ++(Complex &A);
	friend Complex operator ++(Complex &A, int);//后置++,必须额外带参数int区别前置++
};


 Complex operator -(Complex A)//取负数,友元函数类外定义不带类名与作用域符
 {
	 return Complex(-A.real, -A.image);
 }
 Complex operator ++(Complex &A)
 {
	 return Complex(++A.real, A.image);
 }
 Complex operator ++(Complex &A, int)//后置++,必须额外带参数int区别前置++
 {
	 return Complex(A.real++, A.image);
 }

 Complex Complex::operator +(Complex B)//重载运算符为成员函数,省去一个操作数,对象本身充当运算符最左边的操作数;
 {
	 return Complex(real + B.real, image + B.image);
 }

 void Operatoroverloadmain()
{
	 Complex A(100.0, 200.0), B(-10.0, 20.0), C;//实例化
	 cout << "A=", A.display();
	 cout << "B=", B.display();
	 cout << "C=", C.display();
	 C = A + B;
	 cout << "A+B", C.display();
	 C = A - B;
	 cout << "A-B", C.display();
	 C = A++;
	 cout << "C=A++", C.display();
	 cout << "A++=", A.display();

}

int main()
{
  Operatoroverloadmain();//学习运算符重载

}

1.重载运算符,包括重载为类友元函数和类成员函数,实现复数的加减,运算;

2.单目运算符最好重载为类的成员函数,双目运算符则最好重载为类的友元函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值