软件设计(II)教学课件:Chapter7 Operator Overloading and Type Conversions.pptVIP

  • 1
  • 0
  • 约9.49千字
  • 约 32页
  • 2021-11-30 发布于安徽
  • 举报

软件设计(II)教学课件:Chapter7 Operator Overloading and Type Conversions.ppt

Manipulation of Strings To define operators to manipulate the strings For example: string3 = string1 + string2; if( string1 = string2 ) string = string1; An example program overloads + and = * Mathematical operations on strings // overloading + operator String operator+(const String s, const String t){ String temp; temp.len = s.len + t.len; temp.p = new char[temp.len+1]; strcpy(temp.p,s.p); strcat(temp.p,t.p); return temp; } // overloading = operator int operator=(const String s, const String t){ int m = strlen(s.p); int n = strlen(t.p); if(m = n) return(1); else return(0); } Overloadable Operators * Unoverloadable Operators: :: . .* ? : # sizeof A friend cannot be used: = ( ) [ ] - §7.5 Type Conversions Automatic type conversion for built-in types Constants and variables of different types are mixed in an expression Right type of an assignment operator “=“ to the left For example, int m; float x = 3.14159; m = x; What happens when they are user-defined data types? Using Casting operator or Constructor * Three types of situations Conversion from basic type to class type Conversion from class type to basic type Conversion from one class type to another class type * Basic to Class Type Implemented by using constructors with single argument * string::string (char * a) { length = strlen(a); p = new char[length+1]; strcpy(p, a); } string s1,s2; char* name1 = “IBM PC”; char* name2 = “Apple”; s1 = string(name1); s2 = name2; Class to Basic Type By defining an overloaded casting operator Usually referred to as a conversion function: * operator typename(){ ...... ......(Function statements) } Rational::operator double(){ return numerator/denominator; } int main(){ Rational r(2,3); double d = r; } string:: operator char*(){ return (p); } Notes on class ?? basic type It must be a class member It must not specify a return type It must not have any arguments * One Class to Another Class Typ

文档评论(0)

1亿VIP精品文档

相关文档