鱼C论坛

 找回密码
 立即注册
查看: 3181|回复: 1

有關類和對象的問題。

[复制链接]
发表于 2013-5-7 22:52:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 kit1858644 于 2013-5-8 17:07 编辑

想問一下, 以下代碼中為什麼Animal(std::string theName); 不用反回類型?

謝謝。
  1. #include <iostream>
  2. #include <string>

  3. class Animal
  4. {
  5. public:
  6.     Animal(std::string theName);
  7.     void eat();
  8.     void sleep();
  9.     void drool();

  10. protected:
  11.     std::string name;
  12. };

  13. class Pig : public Animal
  14. {
  15. public:
  16.     void climb();
  17.     Pig(std::string theName);
  18. };

  19. class Turtle : public Animal
  20. {
  21. public:
  22.     void swim();
  23.     Turtle(std::string theName);
  24. };

  25. Animal::Animal(std::string theName)
  26. {
  27.     name = theName;
  28. }

  29. void Animal::eat()
  30. {
  31.     std::cout << "I'm eatting!" << std::endl;
  32. }

  33. void Animal::sleep()
  34. {
  35.     std::cout << "I'm sleeping!Don't disturb me!" << std::endl;
  36. }

  37. void Animal::drool()
  38. {
  39.     std::cout << "我是公的,看到母的我会流口水,我正在流口水。。。" << std::endl;
  40. }

  41. Pig::Pig(std::string theName) : Animal(theName)
  42. {
  43. }

  44. void Pig::climb()
  45. {
  46.     std::cout << "我是一个只漂亮的小母猪猪,我会上树,我正在爬树,嘘。。。" << std::endl;
  47. }

  48. Turtle::Turtle(std::string theName) : Animal(theName)
  49. {
  50. }

  51. void Turtle::swim()
  52. {
  53.     std::cout << "我是一只小甲鱼,当母猪想抓我的时候,我就游到海里。。哈哈。。" << std::endl;
  54. }

  55. int main()
  56. {
  57.     Pig pig("小猪猪");
  58.     Turtle turtle("小甲鱼");

  59.     pig.name = "小甲鱼";

  60.     std::cout << "这只猪的名字是: " << pig.name << std::endl;
  61.     std::cout << "每只乌龟都有个伟大的名字: " << turtle.name << std::endl;

  62.     pig.eat();
  63.     turtle.eat();
  64.     pig.climb();
  65.     turtle.swim();

  66.     return 0;
  67. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2013-5-8 12:45:11 | 显示全部楼层
你是问Animal(std::string name)为什么没有返回类型吗?
那是因为构造函数不需要返回值,
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-29 03:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表