#include<iostream.h>
class mammal
{
public:
mammal():itsage(1){}
virtual~mammal(){}
virtual void speak()const{cout<<"mammal speak!\n";}
protected:
int itsage;
};
class dog:public mammal
{
public:
void speak()const{cout<<"woof!\n";}
};
class cat:public mammal
{
public:
void speak()const{cout<<"meow!\n";}
void valuefunction(mammal);
void ptrfunction(mammal*);
void reffunction(mammal&);
int main()
{
mammal*ptr=0;
int choice;
while(1)
{
bool fquit=false;
cout<<"(1)dog(2)cat(0)quit:";
cin>>choice;
switch(choice)
{
case 0:fquit=true;
break;
case 1:ptr=new dog;
break;
case 2:ptr=new cat;
break;
default:ptr=new mammal;
break;
}
if(fquit)
break;
ptrfunction(ptr); //错了吧?
reffunction(*ptr); //错了吧?
valuefunction(*ptr); //错了吧?
}
return 0;
}
void valuefunction(mammal mammalvalue)
{
mammalvalue.speak();
}
void ptrfunction(mammal*pmammal)
{
pmammal->speak();
}
void reffunction(mammal&rmammal)
{
rmammal.speak();
}
(1)dog(2)cat(0)quit:1
woof
woof
mammal speak! //怎么来的?
(1)dog(2)cat(0)quit:2
meow!
meow!
mammal speak! //怎么来的?
(1)dog(2)cat(0)quit:0
森栏