Walk1 a walkthrough with templates
Revision as of 17:49, 4 August 2010 by Catherine.leung (talk | contribs)
/*ABCDEFGHIJKLMNOPQRSTUVWXYZ*/
#include <iostream.h>
class Worm{
int stuff_;
public:
Worm(int x=5){
cout << "Making a Worm. " << endl;
stuff_=x;
}
void operator=(int x){stuff_=(x>0)?x:x+4;}
void operator=(const Worm& w){
stuff_=w.stuff_;
cout << "From one worm to another" << endl;
}
int stuff(){return stuff_;}
};
char operator-(char c,Worm& w){
return c-w.stuff();
}
ostream& operator<<(ostream& os,Worm& w){
os << "A worm: " << w.stuff();
return os;
}
template <class t>
class Bird{
char str_[50];
t val_;
public:
t val(){return val_;}
char* str(){return str_;}
Bird(t val,char* s){
cout << "Fly Birdie! Fly!" << endl;
strcpy(str_,s);
val_=val;
}
void Fly();
~Bird();
};
template <class t>
void Bird<t>::Fly(){
for(int i=0;i<strlen(str_);i++){
str_[i]=str_[i]-val_;
}
}
template <class t>
Bird<t>::~Bird(){
for(int i=0;i<strlen(str_);i++){
if(i%2==0)
str_[i]=str_[i]-val_;
}
cout << "Bye Bye Birdie!" << endl;
cout << str_ << endl;
cout << val_ << endl;
}
int main(void){
Worm wormy;
wormy=-3;
Bird<int> robin(2,"qwwjvqso");
Bird<Worm> sparrow(wormy,"einptjpf");
robin.Fly();
sparrow.Fly();
cout << robin.str() << endl;
cout << sparrow.str() << endl;
}