天天看點

【大學實驗】運算符重載實作複數的運算實驗内容及要求具體代碼實作對于這個實驗的總結和讨論

大學期間學校的一個有關運算符重載的實驗

  • 實驗内容及要求
  • 具體代碼實作
  • 對于這個實驗的總結和讨論

實驗内容及要求

這是一次C++實驗課的實驗,具體如下:

實驗三:運算符重載

要求:

  1. 定義一個複數類Complex,資料成員使用整型變量,重載運算符"+","-",其中"+“使用成員函數重載,”-"使用友元函數重載。
  2. 加法的兩個運算量可以是類對象或整數,順序任意。即c1+c2,c1+i,i+c1(c1,c2為對象名,i為整數)都合法。

    重載"++"單目運算符,運算規則為複數的實部和虛部各加1。

  3. 重載流插入運算符"<<“和流提取運算符”>>",可以使用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指針吧~

繼續閱讀