- 1
- 0
- 约9.49千字
- 约 32页
- 2021-11-30 发布于安徽
- 举报
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
您可能关注的文档
- 高等数学课件:9-7常系数线性微分方程组.ppt
- 高等数学课件:10.1向量及其运算(1-30).ppt
- 高等数学课件:10.2 空间直角坐标系与向量代数(1-24).ppt
- 高等数学课件:10.3 平面与直线.ppt
- 高等数学课件:10.4.1曲面及其方程.ppt
- 高等数学课件:10.4.2二次曲面.ppt
- 高等数学课件:10.5向量函数 空间曲线.ppt
- 高等数学课件:10-1 收敛原理与数项级数.ppt
- 高等数学课件:10-2 正项级数.ppt
- 高等数学课件:10-3任意项级数.ppt
- 软件设计(II)教学课件:Chapter8 Inheritance.ppt
- 软件设计(II)教学课件:Chapter9 Pointers, Virtual Functions and Polymorphism.ppt
- 软件设计(II)教学课件:Chapter10 Console IO Operations.ppt
- 软件设计(II)教学课件:Chapter11 Working with Files.ppt
- 软件设计(II)教学课件:Chapter12 Templates(模板).ppt
- 软件设计(II)教学课件:Chapter13 Exception Handling.ppt
- 软件设计(II)教学课件:Chapter15 String.ppt
- 软件设计(II)教学课件:Chapter17 Object-Oriented Systems Development.ppt
- 软件设计课件:Lecture 01 Introduction.ppt
- 软件设计课件:Lecture 02 Overview of Computers and Programming.ppt
原创力文档

文档评论(0)