| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1184 人关注过本帖
标题:这道程序神奇了,大大们快来看看!
取消只看楼主 加入收藏
小编程员
Rank: 1
来 自:广州
等 级:新手上路
帖 子:14
专家分:0
注 册:2009-7-31
结帖率:75%
收藏
已结贴  问题点数:100 回复次数:0 
这道程序神奇了,大大们快来看看!
#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)函数根本没有运行一样,求教高手!
搜索更多相关主题的帖子: 1234 
2009-08-26 23:29
快速回复:这道程序神奇了,大大们快来看看!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.042002 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved