这道程序神奇了,大大们快来看看!
#include <iostream>using namespace std;
//宠物类别:狗、猫、鸟、鱼、爬行动物、昆虫、其他
enum PetType{DOG, CAT, BIRD, FISH, REPTILE, INSECT, OTHER};
class Pet{ //宠物类
PetType type; //类别
char name[20]; //名字
public:
Pet(PetType type, char name[]){
this->type=type;
// 这里有不同
strcpy(this->name,name);
}
PetType getType()const{ return type; }
const char* getName()const{ return name; }
const char* getTypeString()const{
switch(type){
case DOG: return "a dog";
case CAT: return "a cat";
case BIRD: return "a bird";
case FISH: return "a fish";
case REPTILE: return "a reptile";
case INSECT: return "an insect";
}
return "an unknown animal";
}
void show()const{
cout<<"There is "<<getTypeString()<<" named "<<name<<endl;
}
};
int main(){
Pet a_dog(DOG, "Doggie");
Pet a_cat(CAT, "Mimi");
Pet an_animal(OTHER, "Puppy");
a_dog.show();
a_cat.show();
an_animal.show();
return 0;
}
输出结果为There is a dog named Doggie
There is a cat named Mimi
There is an unknown animal named Puppy
但对name数组的赋值进行了小的更该,输出结果变成了type的改变,真是奇怪了,望高手给予解释!
更改如下:
#include <iostream>
using namespace std;
//宠物类别:狗、猫、鸟、鱼、爬行动物、昆虫、其他
enum PetType{DOG, CAT, BIRD, FISH, REPTILE, INSECT, OTHER};
class Pet{ //宠物类
PetType type; //类别
char name[20]; //名字
public:
Pet(PetType type, char name[]){
this->type=type;
// 这里有不同
for(int i=0;i<=20;i++)this->name[i]=name[i];
}
PetType getType()const{ return type; }
const char* getName()const{ return name; }
const char* getTypeString()const{
switch(type){
case DOG: return "a dog";
case CAT: return "a cat";
case BIRD: return "a bird";
case FISH: return "a fish";
case REPTILE: return "a reptile";
case INSECT: return "an insect";
}
return "an unknown animal";
}
void show()const{
cout<<"There is "<<getTypeString()<<" named "<<name<<endl;
}
};
int main(){
Pet a_dog(DOG, "Doggie");
Pet a_cat(CAT, "Mimi");
Pet an_animal(OTHER, "Puppy");
a_dog.show();
a_cat.show();
an_animal.show();
return 0;
}
输出结果就变为了There is unknown animal named Doggie
There is unknown animal named Mimi
There is an unknown animal named Puppy
好像switch(type)函数根本没有运行一样,求教高手!