本科期间学校的一个有关运算符重载的实验
实验内容及要求
这是一次C++实验课的实验,具体如下:
实验三:运算符重载
要求:
- 定义一个复数类Complex,数据成员使用整型变量,重载运算符"+","-",其中"+“使用成员函数重载,”-"使用友元函数重载。
- 加法的两个运算量可以是类对象或整数,顺序任意。即c1+c2,c1+i,i+c1(c1,c2为对象名,i为整数)都合法。
重载"++"单目运算符,运算规则为复数的实部和虚部各加1。 - 重载流插入运算符"<<“和流提取运算符”>>",可以使用cout<<c1,cin>>c1输出和输入复数。
具体代码实现
#include<iostream>
using namespace std;
class Complex{
public:
Complex(){//构造函数初始化复数为0+0i
this->imag = 0;
this->real = 0;
};
Complex operator + (const Complex& other);//声明复数加复数
Complex operator + (int n);;//声明复数加整数
friend Complex operator + (int a,const Complex& b);//声明整数加复数
friend Complex operator - (const Complex& a,const Complex& b);//声明复数减复数
friend Complex operator - (int a,const Complex& b);//声明整数减复数
friend Complex operator - (const Complex& a,int b);//声明复数减整数
Complex& operator ++ (){//前置++
this->real++;
this->imag++;
return *this;
}
Complex& operator ++ (int){//后置++
Complex a = *this;
a.real++;
a.imag++;
return a;
}
friend ostream& operator << (ostream&,Complex&);//声明重载运算符“<<”
friend istream& operator >> (istream&,Complex&);//声明重载运算符“>>”
private:
int real;//复数的实部
int imag;//复数的虚部
};
Complex Complex::operator + (const Complex& other){//复数加复数的实现
this->real = this->real + other.real;
this->imag = this->imag + other.imag;
return *this;
};
Complex Complex::operator + (int n){//复数加整数的实现
this->real = this->real + n;
return *this;
}
Complex operator + (int a,const Complex& b)//整数加复数的实现
{
Complex result;
result.real=a + b.real;
return result;
}
Complex operator - (const Complex& a,const Complex& b)//复数减复数的实现
{
Complex result;
result.real=a.real - b.real;
result.imag=a.imag - b.imag;
return result;
}
Complex operator - (int a,const Complex& b)//整数减复数的实现
{
Complex result;
result.real=a - b.real;
return result;
}
Complex operator - (const Complex& a,int b)//复数减整数的实现
{
Complex result;
result.real=a.real - b;
return result;
}
ostream& operator << (ostream& output,Complex& c) //定义运算符“<<”重载函数
{
output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;
return output;
}
istream& operator >> (istream& input,Complex& c) //定义重载运算符“>>”重载函数
{
cout<<"请输入复数的实部与虚部(用空格区分):";
input>>c.real>>c.imag;
return input;
}
int main()
{
Complex c1,c2,c3,c4;
cin>>c1;
cin>>c2;
cin>>c3;
c4=c1+1;
cout<<c4;
c4=c3++;
cout<<c4;
c4=++c3;
cout<<c4;
cout<<c3;
return 0;
}
对于这个实验的总结和讨论
实现算数操作符+、-、自增运算符++等一般有两种方法:
- 第一种方法:类操作符
此时,操作符函数是类的成员函数。 - 第二种方法:全局操作符
此时,重载的是全局操作符,需要把一个操作符函数(类似于全局函数)声明为类的友元。
还需要注意的是:
- 算数操作符具有互换性,即左操作与右操作,写代码时应注意重载实现此功能。
- 在程序编写的过程中,本人曾出现后置++与前置++运算符功能写反了的尴尬情况,这是需要注意的,还需要注意的是,在实现自增运算符++的重载时,对于前置的++重载,参数应为空,返回的是this,而对于后置的++重载,参数应为int,这样就可以有所区分,区别,此时返回值依然是this,对于+ -运算符个人认为用全局操作符重载(也就是用友元函数重载)比类操作符重载(也就是用成员函数重载)更加方便快捷,并且思路更为清晰。
- 补充说明: 对于全局操作符重载,不要使用this指针,实例化一个类对象再进行操作,而对于类操作符重载,放心大胆地用this指针吧~
版权声明:本文为qq_30204431原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。