第19讲几种常见的运算符重载及类型转换 教学目的与要求: 了解几种常见的运算符重载函数。 掌握类型转换函数的声明和使用。 教学内容提要: 、几种常见的运算符重载函数 2、类型转换; 教学重点:类型转换 教学难点:几种常见的运算符重载函数。 教学进度:P182~P199 教学过程:
第19讲 几种常见的运算符重载及类型转换 •教学目的与要求: 了解几种常见的运算符重载函数。 掌握类型转换函数的声明和使用。 •教学内容提要: 1、几种常见的运算符重载函数; 2、类型转换; •教学重点:类型转换。 •教学难点:几种常见的运算符重载函数。 •教学进度:P182~P199 •教学过程:
19.1几个常用运算符的重载 191.1单目运算符“++”和“-”的重载 在C+中,可以通过在运算符函数参数表中是否插入关 键字int来区分前缀和后缀这两种方式 ◆对于前缀方式++0b,可以用运算符函数重载为 ob operator ++0; ∥成员函数重载 或 operator+(X&ob);∥友元函数重载, 其中ob为类X对象的引用 ◆对于后缀方式ob++,可以用运算符函数重载为 ob. operator++(int);∥成员函数重载 或 operator++(X&ob,int);∥友元函数重载 在调用后缀方式的函数时参数int一般被传递给值0。 例191:下面是+和运算符的重载的例子:
19.1 几个常用运算符的重载 19.1.1 单目运算符“++”和“--”的重载 在C++中,可以通过在运算符函数参数表中是否插入关 键字int来区分前缀和后缀这两种方式。 ◆对于前缀方式++ob,可以用运算符函数重载为 ob.operator ++(); // 成员函数重载 或 operator ++ (X& ob); // 友元函数重载, 其中ob为类X对象的引用 ◆ 对于后缀方式ob++,可以用运算符函数重载为 ob.operator ++(int); // 成员函数重载 或 operator++(X& ob,int); // 友元函数重载 在调用后缀方式的函数时,参数int一般被传递给值0。 例19.1 :下面是++和--运算符的重载的例子:
#include <iostream.h> class test i int tl, t 2; public: test(int, int); test operator+0;∥前缀 test operator+(int);∥/后缀 test operator-0;∥前缀 test operator-(int);∥后缀 test:: test(int a, int btI=a; t2=b; 1 test test: operator++O 由由 cout<<"++test、n"; ++t1;++t2 return *this:
#include <iostream.h> class test { int t1,t2; public: test(int,int); test operator++(); // 前缀 test operator++(int); // 后缀 test operator--() ; // 前缀 test operator--(int) ; // 后缀 }; test::test(int a,int b){t1=a;t2=b;} test test::operator++() { cout << ″++test \n″; ++t1; ++t2; return *this; } (续)
testtest: operator++(int) {cout<<“test++n”; int tmpl=tI int tmp=t2; t1++:t2++ return test(tmpl, tmp2) testtest: operator--O {cout<<“- - testin”; -t1:--t2 return *this: test test: operator--(int) {cout<“test-Ⅶn”; int tmpl=tl; int tmp=t2 tI: --t2 return test(tmpl, tmp2);
test test::operator++(int) { cout << “test++ \n”; int tmp1=t1; int tmp2=t2; t1++;t2++; return test(tmp1,tmp2); } test test::operator--() { cout << “ —test \n”; --t1;--t2; return *this; } test test::operator--(int) { cout << “test-- \n”; int tmp1=t1; int tmp2=t2; --t1;--t2; return test(tmp1,tmp2); } (续)
void maino test b(3, 4); ++b /t1=4:t2=5 b++ ∥/t1=5:t2=6 b /t1=4:t2=5 ∥tl=3;t2=4 在运算符重载中,++和-后缀运算符被看成一个二元运算符,在其参数类 表中有一个参数声明,但是在这个函数被调用时,这个参数值总为0,函 数内部不需要访问这个参数
void main() { test b(3,4); ++b; // t1=4;t2=5 b++; // t1=5;t2=6 --b; // t1=4;t2=5 b--; // t1=3;t2=4 } 在运算符重载中,++和--后缀运算符被看成一个二元运算符,在其参数类 表中有一个参数声明,但是在这个函数被调用时,这个参数值总为0,函 数内部不需要访问这个参数