运算符重载综合实例
- 格式:doc
- 大小:62.00 KB
- 文档页数:3
第14课运算符重载一、运算符重载的概念1、概念一符多用。
通过重载,对运算符赋予新的含义。
如“+”号,通过重载(C++系统完成),既可以进行整数运算,也可以进行浮点数运算。
2、实例:复数的加法(14_001.cpp)3、上例:对“+”运算符进行重载(14_002.cpp)-------------------------------------------------------------------------------二、运算符重载的规则1、不允许自己定义新的运算符2、不能重载的运算符(1). (成员访问运算符)(2)* (成员指针访问运算符)(3):: (域运算符)(4)sizeof (长度运算符)(5)?: (条件运算符)3、不能改变运算对象的个数4、不能改变运算符的运算级别5、不能改变结合性6、重载运算符的函数不能有默认的参数7、至少有一个参数是自定义的类对象(不能全是C++的标准类型)8、用于类对象的运算符必须重载,有两个例外:“=”“&”9、重载功能应该类似于标准的功能------------------------------------------------------------------------------- 三、运算符重载函数作为友元函数实例:复数相加(14_003.cpp)说明:1、在VC++ 6.0中运行此程序,应修改头两行,见程序。
2、由于友元函数会破坏类的封装性,所以应尽量避免使用。
四、重载双目运算符(有两个操作数,如“+”)1、实例:重载字符串比较运算符“==”、“>”、“<”、“!=”说明:C++的字符串类型,就是对以上的运算符进行了重载,方便了字符串的比较 2、程序(14_004.cpp):以“==”运算符重载为例注意:如果将重载函数定义为友元函数,则程序开头两句应改为:#include <iostream.h>3、重载“+”运算符,对类对象进行相加运算(14_exam.cpp)4、重载“<”运算符,对类对象进行比较(14_011.cpp)5、重载“<”运算符,判断点在不在背景空白处(14_012.cpp)-------------------------------------------------------------------------------五、重载单目运算符1、实例:重载运算符“++”(14_005.cpp)说明:第二个重载函数,多了一个“int”参数,无实际意义,只是与第一个函数区别开来。
实验9 运算符重载(1)一、实验目的1、掌握运算符重载的概念;二、实验内容1、用成员函数重载运算符,使对整型的运算符=、+、-、*、/ 适用于分数运算。
要求:(1)输出结果是最简分数(可以是带分数);(2)分母为1,只输出分子。
过程分析:1) 定义一个类Complex,在公共部分定义构造函数,输出函数,和运算符=、+、-、*、/的重载函数,此处运算符=可以使用系统默认的运算符=的函数。
在私有部分定义两个数据成员x和y。
2) 定义构造函数时先在类里面声明构造函数,并对参数初始化,再在类外定义构造函数,分别给x和y初始化。
3) 定义输出函数print(),对分数进行化简,采用的方法是利用for循环,分子分母均除以i,i从2增加到分子分母中更小的一个数后截止,每次增加1,在利用if else 语句,如果分子分母除以i均被整除,则说明这是的i是分子分母的公约数,分子分母均赋值为整除后的结果值,同时将i重新赋值为2,因为再求公约数是要再从i=2开始循环;否则i++,表示及进入下一个循环。
化成最简形式后在利用if else语句,判断最终结果值的分母是否为1,如果不是,则输出分数,否则只输出分子。
4) 定义运算符+重载函数,参数作为+的右操作对象,调用函数的对象作为左操作对象,在函数里定义一个Complex对象d,将左右操作对象的分数相加,将得到的结果的分子和分母分别赋给d的分子和分母,返回类的对象d。
5) 定义运算符-重载函数,参数作为-的右操作对象,调用函数的对象作为左操作对象,在函数里定义一个Complex对象d,将左右操作对象的分数相减,并将得到的结果的分子和分母分别赋给d的分子和分母,返回类的对象d。
6) 定义运算符*重载函数,参数作为*的右操作对象,调用函数的对象作为左操作对象,在函数里定义一个Complex对象d,将左右操作对象的分数相乘,并将得到的结果的分子和分母分别赋给d的分子和分母,返回类的对象d。
一、为什么要重载操作符1.操作符重载就是把操作符比如+,-,*,/这些运算符赋于新的意义。
2.操作符重载的目的:C++有许多内置的数据类型,包括int,char,double等,每一种类型都有许多运算符,例如加+,减,乘,除等。
当用户定义了类的对象时,两个对象之间是不能进行这些操作的,比如hyong类的对象a+b,这样的语句如果没有重载+运算符就会出错。
但C++允许用户把这些运算符添加到自已的类中以方便类对象之间的运算就像内置类型的运算一样方便,比如对象a+b这样就很明白更容易懂,当然也可以在类中定义一个对象间相加的函数,比如 a.add(b)调用函数add()以实现两个对象a和b相加,但是这条语句没有比a+b更容易让人理解。
3.怎样实现操作符重载:要实现操作符重载就要使用操作符重载函数,操作符重载函数用关见字operator实现,其形式为:反回类型 operator 操作符 (参数列表){}。
操作符重载函数是一个函数,只不过这个函数的函数名为operator再加上后面要重载的操作符而已,比如要重载+号,则: hyong operator +(hyong m){}这就声明了一个反回类型为hyong的操作符函数,其函数名为operator +4.作为类的成员和友元或者独立于类的区别当操作符重载函数作为类的成员函数时,操作符重载函数的参数会比作为友元或者独立于类的操作符重载函数少一个参数,因为操作符重载类成员函数把调用该函数的第一个类的对象作为函数的第一个参数,也就是隐含的this指针指向调用该函数的第一个对象,所以会少一个参数。
5.调用操作符重载函数的方式:5.1 调用类中的操作符重载函数的方法:当调用类中定义的操作符重载函数时最左边的对象是调用操作符重载函数的对象。
比如在类hyong中重定义的+操作符 hyong operator +(hyong m){},有类hyong的对象m和n则调用操作符重载函数的方法有m+n和m.operator +(n),前一条语句会自动转换为后面这条语句,且m+n的表达式中最左边的对象是调用操作符重载函数的对象,而最右边的那个将被作为参数传送。
c++运算符重载经典举例算法运算符重载// A class Complex, and its arithmetic operations.#include <iostream.h>#include <stdlib.h>#include <conio.h>class Complex{public:Complex( float r = 0, float i = 0 ) : _r( r ), _i( i ) {}void print( ) const;friend const Complex operator+(const Complex& x, const Complex& y);friend const Complex operator-(const Complex& x, const Complex& y);friend const Complex operator*(const Complex& x, constComplex& y);friend const Complex operator/(const Complex& x, const Complex& y);private:float _r;float _i;};void Complex::print( ) const{cout<<"_r = " <<_r<<endl;cout<<"_I = "<<_i<<endl;}inline const Complex operator+(const Complex& x, const Complex& y){return Complex( x._r + y._r, x._i + y._i);}inline const Complex operator-(const Complex& x, const Complex& y){return Complex(x._r - y._r, x._i - y._i);}inline const Complex operator*(const Complex& x, const Complex& y){return Complex( x._r * y._r - x._i * y._i, x._r * y._i + x._i * y._r);}const Complex operator/(const Complex& x, const Complex& y) {if (y._r == 0 && y._i == 0){exit(1);}float den = y._r * y._r + y._i * y._i;Complex aComplex((x._r * y._r + x._i * y._i) / den,(x._i * y._r - x._r * y._i) / den);//return Complex((x._r * y._r + x._i * y._i) / den, // (x._i * y._r - x._r * y._i) / den);return aComplex;}int main( ){Complex x(2, 3), y(-1, 3);cout << "x is "; x.print( );cout << "y is "; y.print( );cout << "x + y is ";(x + y).print( );cout << "x - y is ";(x - y).print( );cout << "x * y is ";(x * y).print( );cout << "x / y is ";(x / y).print( );return 0;}引用报告回复sdb新手上路UID 1050精华 0积分 0帖子 24阅读权限 10注册 2007-4-2状态 离线 #2 使用道具 发表于 2007-7-11 14:52 资料 个人空间 短消息 加为好友 重载为成员函数 // A class Complex, and its arithmetic operations. #include <iostream.h>#include <stdlib.h>#include <conio.h>class Complex{public:Complex( float r = 0, float i = 0 ) : _r( r ), _i( i ) {}void print( ) const;const Complex operator+(const Complex& y); const Complex operator-(const Complex& y);const Complex operator*(const Complex& y);const Complex operator/(const Complex& y);private:float _r;float _i;};void Complex::print( ) const{cout<<"_r = " <<_r<<endl;cout<<"_I = "<<_i<<endl;}inline const Complex Complex::opearator+(const Complex& y){return Complex( _r + y._r, _i + y._i);}inline const Complex Complex::operator-(const Complex& y){return Complex(_r - y._r, _i - y._i);}inline const Complex Complex::operator*(const Complex& y){return Complex( _r * y._r - _i * y._i, _r * y._i + _i * y._r);}const Complex Complex::operator/(const Complex& y) {if (y._r == 0 && y._i == 0){exit(1);}float den = y._r * y._r + y._i * y._i;Complex aComplex((_r * y._r + _i * y._i) / den,(_i * y._r - _r * y._i) / den);//return Complex((x._r * y._r + x._i * y._i) / den, // (x._i * y._r - x._r * y._i) / den);return aComplex;}int main( ){Complex x(2, 3), y(-1, 3);cout << "x is "; x.print( );cout << "y is "; y.print( );cout << "x + y is ";(x + y).print( );cout << "x - y is ";(x - y).print( );cout << "x * y is ";(x * y).print( );cout << "x / y is ";(x / y).print( );return 0;}[本帖最后由sdb 于2007-7-11 14:58 编辑]引用报告回复sdb新手上路UID 1050精华 0积分 0帖子 24阅读权限 10注册 2007-4-2状态 离线 #3 使用道具 发表于 2007-7-11 14:53 资料 个人空间 短消息 加为好友 重载下标操作符 // Class Vector is to demonstrator overloading the subscript operator#include <iostream.h>#define size 5class Vector{private:int rep[size];public:const int& operator[ ](int index) const{return rep[index];}int& operator[ ](int index){return rep[index];}};// Using the overloaded operator [ ], this function does not access// the private member of class Vectorostream& operator<<(ostream& out, const Vector& a) {for (int i = 0; i < size; ++i){out << a <<endl;//out<<a.rep;// the const version of operator[ ] is used }return out;}int main( ){Vector x;cout << "Enter " << size << " integers.\n";for (int i = 0; i < size; ++i){cin >> x;} // the non-const version of operator [ ] is usedconst Vector y = x;cout <<"y = ";cout << y;x[0] = 1; // Non-const version againcout <<"y = ";cout<< y;cout <<"x = ";cout<<x;return 0;////////////////////////////////////////////////////// This example defines the second version of the class Vector, which has overloaded operators =, // [ ] and <<.#include <iostream.h>class Vector{public:Vector(int s, int an_array[ ]); // a constructor~ Vector( ){delete [ ] rep;} // a destructorint get_size( ) const {return size;} // an accessorconst Vector& operator=(const Vector& x);int& operator[ ](int index) { return rep[index]; }const int& operator[ ](int index) const { return rep[index];}private:int *rep;int size;};// A constructor initializing the members of rep by the parameter an_arrayVector:: Vector(int s, int an_array[ ]) : size(s), rep( new int[s] ){for (int i = 0; i < size; ++i){rep = an_array;}}// Note that the initializer uses new int[s] to initialize rep, but not new int[size]// because the initializers may not be evaluated in the specified order.const Vector& Vector::operator=(const Vector& x){if( this != &x){size = x.size;delete [ ] rep; // clean up the old one.rep = new int[size];for (int i = 0; i < size; ++i){rep = x.rep;}}return *this;}ostream& operator<<(ostream& out, const Vector& x) {int s = x.get_size( );for (int i = 0; i < s; ++i){out << x<<endl;}return out;}int main(){int array[5] = { 1, 2, 3, 4, 5 };Vector v1( 5, array );cout<<"v1= "<<v1<<endl;Vector v2 = v1;cout<<"v2= "<<v2<<endl;v1[4] = 100;cout<<"v2= "<<v2<<endl;return 0;}[本帖最后由sdb 于2007-7-11 14:58 编辑]引用报告回复sdb新手上路UID 1050精华 0积分 0帖子 24阅读权限 10注册 2007-4-2状态 离线 #4 使用道具 发表于 2007-7-11 14:54 资料 个人空间 短消息 加为好友 输出符重载 // To illustrate the dangers of the default assignment with dynamic memory allocation.#include <iostream.h>#include <string.h>const int MAX_CHAR = 10;class Account{friend ostream& operator<<(ostream& os, Account &b);public:Account ( char* name ="unknown", char* mr = "Miss", float y=0.0){title= new char[strlen(mr)+1];strcpy(title,mr);strcpy(owner, name);balance = y;}void changetitle(char* newname){if( strlen(newname) > strlen(title) ) {delete []title;title = NULL;title = new char[strlen(newname)+1];strcpy( title, newname );}else{strcpy(title, newname);}}void changename(char* newname){strcpy( owner, newname );}~Account (){delete [ ] title;}private:char* title;char owner[MAX_CHAR];float balance;};ostream& operator<< (ostream& os, Account &b){os <<"who:"<< b.title << " " << b.owner <<" how much="<<b.balance<<"\n";os << endl;return os;}void main(){Account acc("Lou","Mr", 100);Account acc1;cout << acc;cout << acc1;acc1=acc;cout << acc1;acc1.changename("jean");cout << acc1;cout<<acc;acc1.changetitle("Dr.");cout << acc1;cout<<acc;}引用报告回复sdb新手上路UID 1050精华 0积分 0帖子 24阅读权限 10注册 2007-4-2状态 离线 #5 使用道具 发表于 2007-7-11 14:59 资料 个人空间 短消息 加为好友 容器的构造 // The following is another version of the class Vector with three constructors, a destructor (which // is the same as in the previous example), an overloaded assignmentoperator , an overloaded// output operator , and an overloaded equality operator .#include <iostream.h>class Vector{private:int *rep;int size;void clone(const Vector& a);void dispose( );public:Vector(int s=0);// a default constructor initializing all members of repto 0 if s is not 0.Vector(int *, int);// a constructor creates a Vector object from an ordinary arrayVector(const Vector& v); // a copy constructor~Vector( ) {dispose( );} // a destructor int get_size( ) const {return size;} // an accessorconst Vector& operator=(const Vector& x);int& operator[ ](int index) {return rep[index];}const int& operator[ ](int index) const {return rep[index];}};void Vector::clone(const Vector& a){this->size = a.size;rep = new int[size];for (int count = 0; count < size; ++count)rep[count] = a[count];}void Vector::dispose( ){ delete [ ] rep; }Vector::Vector(int s) : size(s){if (size <= 0){ rep = NULL; }else{rep = new int[size];for (int count = 0; count < size; ++count){ rep[count] = 0; }}}Vector::Vector(int * a, int s) : size(s), rep(new int[s]) {for (int count = 0; count < size; ++count){ rep[count] = a[count]; }}Vector::Vector(const Vector& v){ clone(v); }//for example: Vector a, v; a.=(v);const Vector& Vector::operator=(const Vector& x) {if ( this != &x ){delete []rep;this->size = a.size;rep = new int[size];for (int count = 0; count < size; ++count)rep[count] = a[count];}return *this;}// overloading operator <<, not a friend function ostream& operator<<(ostream& out, const Vector& x) {int s = x.get_size( );for (int i = 0; i < s; ++i){out << x<<endl;}out << endl;return out;}bool operator==(const Vector& a, const Vector& b) {bool yes = true;if (a.get_size( ) != b.get_size( )){ yes = false; }else{int s, index = 0;s = a.get_size( );while (index < s && a[index] == b[index]){ ++index; }if (index < s){ yes = false; }}return yes;}引用报告回复sdb新手上路UID 1050精华 0积分 0帖子 24阅读权限 10注册 2007-4-2状态 离线 #6 使用道具 发表于 2007-7-11 15:01 资料 个人空间 短消息 加为好友 类型转换 // The following example demonstrates when a constructor or a destructor is called:#include <iostream.h>class Demo{private:int i;public:// default constructorDemo(int n = 0) : i(n) {cout << "default constructor called\n";}// copy constructor: for example Demo b(a);Demo(const Demo& a){i = a.i;cout << "copy constructor called\n";}// destructor~Demo( ) {cout << "destructor called\n";}// assignment operatorconst Demo& operator=(const Demo& a){this->i = a.i;cout << "assignment operator used\n";return *this;}Demo& set_value(int n) {i = n; return *this;}// returning an object to facilitate function chainint get_value( ) {return i;}};Demo foo(Demo x)// pass by value to invoke copy constructor{Demo d;return d; // returning a localobject by value}int main( ){Demo a(2);{Demo b;b = foo(a);}Demo c = a;return 0;}引用报告回复sdb 新手上路U I D 1050精华 0积分 0帖子 24阅读权限10 注册2007-4-2状态 离线#7使用道具 发表于 2007-7-11 15:02 资料 个人空间 短消息 加为好友字符串的构造// Constructor type conversion#include <iostream.h>#include <string.h>class String{int len;char * rep;public:String( ) : len(0)// default constructor {rep = new char[1];strcpy(rep, "");}String(char * s)// another constructor {if (!s){len = 0;s = new char[1];strcpy(rep, "");}else{len = strlen(s);rep = new char[len + 1];strcpy(rep, s);}}String(const String& str) : len(str.len), rep(new char[str.len + 1]) // copy constructor{strcpy(rep, str.rep);}~String( ) // destructor{delete [ ] rep;}friend void print(const String& s); };void print(const String& s){cout << s.rep << " ";return;}int main( ){char * a = "first string";print(a);print("second string");String b = "bad initialization"; print(b);return 0;}引用报告回复sdb新手上路UID 1050精华 0积分 0帖子 24阅读权限 10注册 2007-4-2状态 离线 #8 使用道具 发表于 2007-7-11 15:04 资料 个人空间 短消息 加为好友 // The following program defines four arrays of objects in class Item. The first array initializes the // objects by calling the constructor explicitly. The second array uses the type conversion feature // of the constructor . Thethird array and the fourth arrays use the default values of the// constructor .#include <iostream.h>#include <string.h>class Item{char * name;int id;public:Item( ) : name(new char[1]), id(0) {strcpy(name, "");} Item(char * s, int i = 0) : id(i), name(new char[strlen(s) + 1]){ strcpy(name, s); }void set(char * s, int i){if( name ) delete [ ] name;name = new char[strlen(s) + 1];strcpy(name, s);id = i;}~Item( ) {delete [ ] name;}friend ostream& operator << (ostream& out, const Item& i);};ostream& operator << (ostream& out, const Item& i) {out << endl << << i.id << endl;return out;}int main( ){Item stationary[2] = {Item("pen", 1), Item("notebook", 2)};Item meat[3] = {"pork", "beef", "chicken"};Item nothing[2];Item * ptr = new Item[3];for (int count = 0; count < 2; ++count){ cout << stationary[count]; }for (int count = 0; count < 3; ++count){ cout << meat[count]; }for (int count = 0; count < 2; ++count){nothing[count].set("array", count + 1);cout << nothing[count];}for (int count = 0; count < 3; ++count){ptr[count].set("dynamic array", count + 1);cout << ptr[count];}delete [ ] ptr;return 0; }。
C++中运算符重载的规则语法实例运算符重载,就是对已有的运算符重新进⾏定义,赋予其另⼀种功能,以适应不同的数据类型。
之前就知道运算符的重载就是将它重新定义,给它新的功能,为的式符合程序员的要求,⼀个例⼦就是,要将坐标相加,但是电脑不知道怎么相加,于是聪明的⼈就赋予了“+”新的定义。
然⽽⼀些严格意义上的⽤法还不是很清楚。
现在就在这总结⼀下。
⾸先运算符重载的规则如下:①、 C++中的运算符除了少数⼏个之外,全部可以重载,⽽且只能重载C++中已有的运算符。
不能重载的运算符只有五个,它们是:成员运算符“.”、指针运算符“*”、作⽤域运算符“::”、“sizeof”、条件运算符“?:”。
②、重载之后运算符的优先级和结合性都不会改变。
③、运算符重载是针对新类型数据的实际需要,对原有运算符进⾏适当的改造。
⼀般来说,重载的功能应当与原有功能相类似,不能改变原运算符的操作对象个数,同时⾄少要有⼀个操作对象是⾃定义类型。
运算符重载为类的成员函数的⼀般语法形式为:函数类型 operator 运算符(形参表){函数体;}⼲脆将⼀些运算符重新列出下⼀下:可以⽤作重载的运算符:算术运算符:+,-,*,/,%,++,--;位操作运算符:&,|,~,^,<<,>>逻辑运算符:!,&&,||;⽐较运算符:<,>,>=,<=,==,!=;赋值运算符:=,+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=;其他运算符:[],(),->,,(逗号运算符),new,delete,new[],delete[],->*下列运算符不允许重载:.,.*,::,?:(上⾯也说了的)下⾯给例⼦Boxoperator+(const Box&, const Box&);声明加法运算符⽤于把两个 Box 对象相加,返回最终的 Box 对象。
⼤多数的重载运算符可被定义为普通的⾮成员函数或者被定义为类成员函数。
1.赋值函数的重载示例程序代码如下#include "stdafx.h"#include <malloc.h>class stack{private:int *sp, top, max;void inflate();public:stack(int size = 10){sp = (int *)malloc(sizeof(int) * size); max = size;top = 0;}int pop();void push(int value);stack & operator=(stack & rightValue); };//栈的容量增倍void stack::inflate(){int index, *tp;tp = (int *)malloc(sizeof(int) * max * 2); for(index = 0; index < top; index++){tp[index] = sp[index];}max += max;free(sp);sp = tp;}//出栈int stack::pop(){if(top <= 0)throw 1;return sp[--top];}//入栈void stack::push(int value){if(top == max)inflate();sp[top++] = value;}//赋值函数stack & stack::operator=(stack & rightValue){top = rightValue.top;max = rightValue.max;sp = (int *)malloc(sizeof(int) * max);for(int index = 0; index < max; index++){sp[index] = rightValue.sp[index];}return *this;}void main(){stack x(100), y, z;z = y = x;}这里要注意的是赋值函数的返回值是stack &,这是为了实现链式表达式,如z = y = x;。
运算符重载综合实例class MyComplex{ double Real;double Imag;public://构造函数MyComplex(const double &r=0.0,const double &i=0.0){Real=r;Imag=i;cout<<"Constructor !"<<endl;} //拷贝构造函数MyComplex(const MyComplex &);double GetReal(){return Real;}double GetImag(){return Imag;}//赋值运算符重载为成员函数MyComplex operator=(const MyComplex &c);//负数运算符重载为成员函数MyComplex operator-();//后缀加1,成员函数MyComplex operator++(int);//后缀减1,外部函数friend MyComplex operator--(MyComplex &,int);//加法,外部函数friend MyComplex operator+(const MyComplex &, const MyComplex &);//减法,成员函数MyComplex operator-(const MyComplex &);//加赋值,成员函数MyComplex operator+=(const MyComplex &);//比较,外部函数和friend int operator==(const MyComplex &, const MyComplex &);};MyComplex operator--( MyComplex &c,int){MyComplex result(c.Real--,c.Imag--);cout<<"operatorpostfix--"<<endl;return result;}MyComplex operator+(const MyComplex &c1, const MyComplex &c2){MyComplex result(c1.Real+c2.Real,c1.Imag+c2.Imag);cout<<"operator+"<<endl;return result;}int operator==(const MyComplex &c1, const MyComplex &c2){cout<<"operator=="<<endl;return (c1.Real==c2.Real)&&(c1.Imag==c2.Imag);}MyComplex::MyComplex(const MyComplex &c){Real=c.Real;Imag=c.Imag;cout<<"Copy Constructor !"<<endl;}MyComplex MyComplex::operator=(const MyComplex &c){Real=c.Real;Imag=c.Imag; cout<<"operator="<<endl;return *this;} MyComplex MyComplex::operator-(){Real=-Real;Imag=-Imag;cout<<"operatorunary-"<<endl;return *this;}MyComplex MyComplex::operator++(int){MyComplex result(Real++,Imag++);cout<<"operatorpostfix++"<<endl; return result;}MyComplex MyComplex::operator-(const MyComplex &c){Real-=c.Real; Imag-=c.Imag;cout<<"operatorbinary-"<<endl;return *this;} MyComplex MyComplex::operator+=(const MyComplex &c){Real+=c.Real; Imag+=c.Imag; cout<<"operator+="<<endl; return *this;}void main(){MyComplex a(10,20),b(11,21),e,*p;MyComplex c(a);MyComplex d=b;d+=c++;e=((a+b)-(c--))+(-d);p=new MyComplex(21,22);if(!p) return;e+=(d==(*p));if(p) delete p;cout<<a.GetReal()<<"+j"<<a.GetImag()<<endl;cout<<b.GetReal()<<"+j"<<b.GetImag()<<endl;cout<<c.GetReal()<<"+j"<<c.GetImag()<<endl;cout<<d.GetReal()<<"+j"<<d.GetImag()<<endl;cout<<e.GetReal()<<"+j"<<e.GetImag()<<endl;}Constructor !Constructor !Constructor !Copy Constructor !Copy Constructor !Constructor !operatorpostfix++Copy Constructor !operator+=Copy Constructor !operatorunary-Copy Constructor !Constructor !operatorpostfix--Copy Constructor !Constructor !operator+Copy Constructor ! operatorbinary- Copy Constructor ! Constructor ! operator+Copy Constructor ! operator=Copy Constructor ! Constructor ! operator== Constructor ! operator+=Copy Constructor ! 10+j2011+j2110+j20-21+j-41-11+j-21。
//对于成员函数重载运算符而言,双目运算符的参数表中仅有一个参数,而单目则无参数。
同样的是重载,由于友元函数没有this指针,因此//在参数的个数上会有所区别的。
//***对运算符”+“的重载***/*#include<iostream>using namespace std;class trans{public:trans(int x=100){cha=x;}int operator+(int b);int cha;};int trans::operator+(int b){return cha-b;}int main(){trans t(90);int sum=10;sum=t.operator+(sum); //重载运算符”+“的显式调用//sum=t+sum; 重载运算符“+”的隐式调用cout<<sum<<endl;system("pause");return 0;}*///说明:在作为成员函数的情况下,对”+“运算符的重载所包含的参数个数只能有零个或一个。
//*** 对运算符”++“的重载一***//运算符"++"前置的情况/*#include<iostream>using namespace std;class trans{public:trans(int x=100){cha=x;}int operator++();int cha;};int trans::operator++(){return cha-1;}int main(){trans t(90);int sum;//sum=t.operator++(); //重载运算符”++“的显式调用sum=++t; //重载运算符“++”的隐式调用cout<<sum<<endl;system("pause");return 0;}*///*** 对运算符"++"的重载二***//运算符"++"后置的情况/*#include<iostream>using namespace std;class trans{public:trans(int x=100){cha=x;}int operator++(int);int cha;};int trans::operator++(int){return cha-9;}int main(){trans t(100);int sum;int arg; //仅在显式调用用到该参数。
简述运算符重载的规则。
篇一:运算符重载是C/C++语言中一种强大的功能,允许程序员自定义函数的行为,以处理不同类型的数据。
运算符重载允许程序员在函数中重载算术、逻辑和位运算符,从而能够处理数组、结构体和指针等不同类型的数据。
以下是运算符重载的规则:1. 算术运算符重载算术运算符包括加号、减号、乘号和除号。
每个算术运算符都有一组默认的行为,可以通过运算符重载来自定义它们的行为。
例如,重载加号运算符可以使函数接受一个整数参数,并返回一个新的整数。
下面是一个简单的例子,演示了如何重载加号运算符:```c++struct MyStruct {int value;};MyStruct operator+(const MyStruct& other, int value) {return MyStruct(value + other.value);}int main() {MyStruct mystruct1 = { 10 };MyStruct mystruct2 = { 20 };int result = mystruct1 + mystruct2;std::cout << "result = " << result << std::endl;return 0;}```在上面的例子中,我们定义了一个名为`MyStruct`的结构体类型,其中包含一个整数类型。
然后,我们定义了一个重载加号运算符的函数,该函数接受一个整数类型的参数,并返回一个新的`MyStruct`对象。
在`main`函数中,我们定义了两个`MyStruct`对象`mystruct1`和`mystruct2`,并将它们相加,结果存储在`result`变量中。
2. 逻辑运算符重载逻辑运算符包括条件运算符和逻辑非运算符。
每个逻辑运算符都有一组默认的行为,可以通过运算符重载来自定义它们的行为。
运算符重载综合实例
class MyComplex{ double Real;double Imag;
public:
//构造函数
MyComplex(const double &r=0.0,const double &i=0.0){Real=r;Imag=i;cout<<"Constructor !"<<endl;} //拷贝构造函数
MyComplex(const MyComplex &);
double GetReal(){return Real;}
double GetImag(){return Imag;}
//赋值运算符重载为成员函数
MyComplex operator=(const MyComplex &c);
//负数运算符重载为成员函数
MyComplex operator-();
//后缀加1,成员函数
MyComplex operator++(int);
//后缀减1,外部函数
friend MyComplex operator--(MyComplex &,int);
//加法,外部函数
friend MyComplex operator+(const MyComplex &, const MyComplex &);
//减法,成员函数
MyComplex operator-(const MyComplex &);
//加赋值,成员函数
MyComplex operator+=(const MyComplex &);
//比较,外部函数和
friend int operator==(const MyComplex &, const MyComplex &);
};
MyComplex operator--( MyComplex &c,int){MyComplex result(c.Real--,c.Imag--);
cout<<"operatorpostfix--"<<endl;return result;}
MyComplex operator+(const MyComplex &c1, const MyComplex &c2){
MyComplex result(c1.Real+c2.Real,c1.Imag+c2.Imag);
cout<<"operator+"<<endl;
return result;
}
int operator==(const MyComplex &c1, const MyComplex &c2){
cout<<"operator=="<<endl;
return (c1.Real==c2.Real)&&
(c1.Imag==c2.Imag);
}
MyComplex::MyComplex(const MyComplex &c){
Real=c.Real;Imag=c.Imag;cout<<"Copy Constructor !"<<endl;}
MyComplex MyComplex::operator=(const MyComplex &c){
Real=c.Real;Imag=c.Imag; cout<<"operator="<<endl;return *this;} MyComplex MyComplex::operator-(){Real=-Real;Imag=-Imag;
cout<<"operatorunary-"<<endl;return *this;}
MyComplex MyComplex::operator++(int){MyComplex result(Real++,Imag++);
cout<<"operatorpostfix++"<<endl; return result;}
MyComplex MyComplex::operator-(const MyComplex &c){
Real-=c.Real; Imag-=c.Imag;cout<<"operatorbinary-"<<endl;return *this;} MyComplex MyComplex::operator+=(const MyComplex &c){
Real+=c.Real; Imag+=c.Imag; cout<<"operator+="<<endl; return *this;}
void main(){
MyComplex a(10,20),b(11,21),e,*p;
MyComplex c(a);
MyComplex d=b;
d+=c++;
e=((a+b)-(c--))+(-d);
p=new MyComplex(21,22);
if(!p) return;
e+=(d==(*p));
if(p) delete p;
cout<<a.GetReal()<<"+j"<<a.GetImag()<<endl;
cout<<b.GetReal()<<"+j"<<b.GetImag()<<endl;
cout<<c.GetReal()<<"+j"<<c.GetImag()<<endl;
cout<<d.GetReal()<<"+j"<<d.GetImag()<<endl;
cout<<e.GetReal()<<"+j"<<e.GetImag()<<endl;
}
Constructor !
Constructor !
Constructor !
Copy Constructor !
Copy Constructor !
Constructor !
operatorpostfix++
Copy Constructor !
operator+=
Copy Constructor !
operatorunary-
Copy Constructor !
Constructor !
operatorpostfix--
Copy Constructor !
Constructor !
operator+
Copy Constructor ! operatorbinary- Copy Constructor ! Constructor ! operator+
Copy Constructor ! operator=
Copy Constructor ! Constructor ! operator== Constructor ! operator+=
Copy Constructor ! 10+j20
11+j21
10+j20
-21+j-41
-11+j-21。