实验目的:
1.掌握C++语言多态性的基本概念
2.掌握运算符重载函数的声明和定义方法
运算符重载:
1.运算符重载是通过创建运算符重载函数来实现的,运算符重载函数可以是在类外定义的普通函数,也可以是类的成员函数或友元函数。
C++为运算符重载提供了一种方法,即在进行运算符重载时,必须定义一个运算符重载函数,其名字为operator,后随一个要重载的运算符。
2.运算符重载的函数格式:
3.C++中绝大多数的运算符允许重载,不能重载的运算符有以下几个:
. 成员访问运算符;
.* 成员指针访问运算符;
:: 作用域运算符;
Sizeof 长度运算符;
?: 条件运算符;
4.C++语言只能已有的运算符进行重载,不允许用户自己定义运算符;
#include<iostream>
using namespace std;
class complex {
public:
double real;
double imag;
complex(double r = 0, double i = 0) {
real = r;
imag = i;
}
void print();
void input(complex );
};
//类外定义
complex operator*(complex co1, complex co2) {
complex temp;
temp.real = co1.real * co2.real - co1.imag * co2.imag;
temp.imag = co1.real * co2.imag + co1.imag * co2.real;
return temp;
}
void complex:: print() {
cout << "mcl real=" << real << " " << "mcl imag=" << imag << endl;
}
void complex::input(complex