继承

发布时间 2023-07-23 21:27:01作者: hacker_dvd
#include <iostream>

// 基类 Animal
class Animal {
 public:
  Animal() {}
  Animal(const Animal& other) {
    std::cout << "Animal Copy Constructor" << std::endl;
  }
  virtual ~Animal() {}
  virtual void makeSound() const {
    std::cout << "Animal Sound" << std::endl;
  }
};

// 派生类 Dog
class Dog : public Animal {
 public:
  Dog() {}
  void makeSound() const override {
    std::cout << "Woof!" << std::endl;
  }
};

// 派生类 Cat
class Cat : public Animal {
 public:
  Cat() {}
  void makeSound() const override {
    std::cout << "Meow!" << std::endl;
  }
};

// 函数,接受 Animal 类型的引用参数
void animalFunction(Animal& animal) {
  animal.makeSound();
}

// 函数,接受 Animal 类型的常量引用参数
void constantAnimalFunction(const Animal& animal) {
  animal.makeSound();
}

int main() {
  Dog dog;
  Cat cat;

  // 使用派生类对象调用函数,派生类向基类的类型转换
  animalFunction(dog);  // Output: Woof!

  // 使用派生类对象调用常量引用函数,派生类向基类的类型转换
  constantAnimalFunction(cat);  // Output: 

  // 非常量引用函数不能使用临时对象调用,会编译失败
  // animalFunction(Dog());

  // 使用派生类对象的临时对象调用常量引用函数,涉及拷贝构造函数调用
  constantAnimalFunction(Dog());  // Output: Woof!

  return 0;
}