12.010 Computational Methods of Scientific Programming Lecture 10
-
Upload
calista-riley -
Category
Documents
-
view
20 -
download
0
description
Transcript of 12.010 Computational Methods of Scientific Programming Lecture 10
12.010 Computational Methods of Scientific Programming
Lecture 10
Today’s lecture
•Inheritance and overloading in C++Web page http://www-gpsg.mit.edu/~tah/12.010
12.010 2
Previous Lecture
• Basic features of C++
– Adds formal classclass concept to C, making it object-oriented
– ClassClass is like a derived type except• It is better encapsulated
• It has “methodsmethods”
• Invoking a method is like sending a message to the object, object contains its own logic saying what to do.
– E.g the String class
String s1;
s1.set(“Hello”);
printf(“%s\n”,s1.ss());
12.010 3
Inheritance
String
set()s()
Want new class uString. Like String except that the stringswill be converted and stored in upper case.e.g.
uString
set()s()
String s;s.set(“Hello”);printf(“%s\n”,s.s());Hello
uString s;s.set(“Hello”);printf(“%s\n”,s.s());HELLO
12.010 4
uString extends String
• No need to write uString from scratch.
• Inherit most code from String.
• Extend String::set to capitalise.
• A uString is a String with some extra feature.
String
set()s()
uString
Base class
Derived class
12.010 5
• New interface for uString
/* Extend String class to uString */
/* uString stores strings as upper case */
class uString : public String {
public:
void set( char *); /* Set a uString */
};
C++ Inheritance Example
12.010 6
/* Set str to point to a private copy of s */
void uString::set(char *s) {
int i;
String::set(s);
for (i=0;i<strlen(s);++i) {
if ( str[i] >= 'a' && str[i] <= 'z' ) {
str[i] = toupper(str[i]);
}
}
}
uString setset method
Base class methodBase class method
““protected” protected” (not “private”)(not “private”)
12.010 7
main(){ String s1; uString s2;
printf("Executable code starting\n");
s1.set("Hello"); printf("%s\n",s1.s()); s2.set("Hello"); printf("%s\n",s2.s());
printf("Executable code ending\n");}
uString in action!
12.010 8
Overloading
coord
=()+()
Can redefine operators e.g. + to operate on classese.g.
coord p1, p2, p3;p3 = p1 + p2
This would then doif p1=p2=(1,1,1) p3 = (2,2,2)
12.010 9
Overloading
Have to define the meaning of + and = for a coordcoord classobject. Language defines meaning for integer, float, doubleetc but now we can define extra meanings.
class coord{
public:
coord operator+(coord );
private:
int cx; int cy; int cz;
};
coord coord::operator+ (coord c2)
{
coord temp;
temp.cx = cx + c2.cx;
temp.cy = cy + c2.cy;
temp.cz = cz + c2.cz;
return(temp);
}
12.010 10
Homework
• http://mitgcm.org/~cnh/12.010/Lec10/homework3.html
• Due Oct 27th
• E-mail homework and question to [email protected]