|
发表于 2022-1-9 00:09:21
|
显示全部楼层
本楼为最佳答案
 - #include <iostream>
- #include <string>
- class Animal
- {
- public:
- std::string mouth;
- Animal(std::string theName);//构造器
- void eat();
- void sleep();
- void drool();
- std::string getName(); // 这里 <-----------------------------------------------
- protected:
- std::string name;
- };
- class Pig : public Animal
- {
- public:
- void climb();
- Pig(std::string theName); //构造器
- };
- class Turtle : public Animal
- {
- public:
- void swim();
- Turtle(std::string theName);//构造器
- };
- Animal::Animal(std::string theName)
- {
- name = theName;
- }
- Pig::Pig(std::string theName) : Animal(theName)
- {
- }
- Turtle::Turtle(std::string theName) : Animal(theName)
- {
- }
- void Animal::eat()
- {
- std::cout << "I am eating!" << std::endl;
- }
- void Animal::sleep()
- {
- std::cout << "I am sleeping!" << std::endl;
- }
- void Animal::drool()
- {
- std::cout << "我想挑战一下我的极限!" << std::endl;
- }
- std::string Animal::getName() // 这里 <-----------------------------------------------
- {
- return name;
- }
- void Pig::climb()
- {
- std::cout << "我会上树,没想到吧!" << std::endl;
- }
- void Turtle::swim()
- {
- std::cout << "我是一只小甲鱼,当有人要捉我的时候,我就缩头。。。" << std::endl;
- }
- int main(void)
- {
- Pig pig("B");
- Turtle turtle("老乌龟");
- // pig.name = "A";
-
- std::cout << "这只猪的名字是:" << pig.getName() << std::endl; // 打印 <-----------------------------------------------
- std::cout << "小甲鱼的名字是:" << turtle.getName() << std::endl; // 打印 <-----------------------------------------------
- pig.eat();
- turtle.eat();
- pig.climb();
- turtle.swim();
-
- return 0;
- }
复制代码 |
|