《程序设计实习》 4. 运算符重载.pptVIP

  • 1
  • 0
  • 约1.05万字
  • 约 80页
  • 2021-08-03 发布于湖北
  • 举报
程序设计实习;信息科学技术学院《程序设计实习》 郭炜;运算符重载的需求;运算符重载的需求;运算符重载;运算符重载的形式;运算符重载的形式;运算符重载的形式;运算符重载的形式;运算符重载的形式;运算符重载的形式;运算符重载示例 (P209);int main() { Complex a(4,4),b(1,1),c; c = a + b; //等价于c=operator+(a,b); cout c.real , c.imag endl; cout (a-b).real , (a-b).imag endl; //a-b等价于a.operator-(b) return 0; } 输出: 5,5 3,3 c = a + b; 等价于c=operator+(a,b); a-b 等价于a.operator-(b) ;信息科学技术学院《程序设计实习》 郭炜;信息科学技术学院《程序设计实习》 郭炜;信息科学技术学院《程序设计实习》 郭炜; 有时候希望赋值运算符两边的类型可以不匹配,比如,把一个int类型变量赋值给一个Complex对象,或把一个 char * 类型的字符串赋值给一个字符串对象,此时就需要重载赋值运算符“=”。 赋值运算符“=”只能重载为成员函数 ;class String { private: char * str; public: String ():str(NULL) { } const char * c_str() { return str; }; String operator = (const char * s); String::~String( ); }; String String::operator = (const char * s) { //重载“=”以使得 obj = “hello”能够成立 if( str) delete [] str; if(s) { //s不为NULL才会执行拷贝 str = new char[strlen(s)+1]; strcpy( str, s); } else str = NULL; return * this; };String::~String( ) { if( str) delete [] str; }; int main() { String s; s = Good Luck, ; //等价于 s.operator=(Good Luck,); cout s.c_str() endl; // String s2 = hello!; //这条语句要是不注释掉就会出错 s = Shenzhou 8!; //等价于 s.operator=(Shenzhou 8!); cout s.c_str() endl; return 0; } 输出: Good Luck, Shenzhou 8! ;浅拷贝和深拷贝(P213);str;str;如不定义自己的赋值运算符,那么S1=S2实际上导致 和 S2.str 指向同一地方。 ;如不定义自己的赋值运算符,那么S1=S2实际上导致 和 S2.str 指向同一地方。 如果S1对象消亡,析构函数将释放 指向的空间,则S2消???时还要释放一次,不妥。;如不定义自己的赋值运算符,那么S1=S2实际上导致 和 S2.str 指向同一地方。 如果S1对象消亡,析构函数将释放 指向的空间,则S2消亡时还要释放一次,不妥。 另外,如果执行 S1 = other;会导致指向的地方被delete 因此要在 class MyString里添加成员函数: String operator = (const String s) { if( str) delete [] str; str = new char[strlen( s.str)+1]; strcpy( str,s.str); return * this; };如不定义自己的赋值运算符,那么S1=S2实际上导致 和 S2.str 指向同一地方。 如果S1对象消亡,析构函数将释放 指向的空间,则S2消亡时还要释放一次,不妥。 另外,如果执行 S1 = other;会导致指向的地方被delete 因此要在 class MyString里添加成员函数: String operator = (const String s) { if( str) delete [] str; str = new char[strle

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档