C++如何实现类的继承与多态?(代码示例)

7次阅读

C++ 中继承用: 语法实现,多态依赖 virtual 函数和基类指针 / 引用调用;公有继承保持访问级别,派生类不继承构造函数、析构函数、赋值运算符和友元函数。

C++ 如何实现类的继承与多态?(代码示例)

在 C ++ 中,继承通过 : 语法实现,多态依赖虚函数(virtual)和基类指针 / 引用调用。核心是“用基类接口操作派生类对象”,运行时决定调用哪个版本的函数。

1. 基础继承:公有继承与成员访问

派生类默认不继承构造函数、析构函数、赋值运算符和友元函数。常用的是公有继承(public),保持基类成员的访问级别不变:

class Animal {protected:     std::string name; public:     Animal(const std::string& n) : name(n) {}     void introduce() {std::cout << "I'm "<< name << std::endl;} }; 

class Dog : public Animal {// 公有继承 public: Dog(const std::string& n) : Animal(n) {} void bark() {std::cout << name <<" says: Woof!"<< std::endl;} };

// 使用 Dog d("Buddy"); d.introduce(); // OK:继承自 Animal 的 public 成员 d.bark(); // OK:Dog 自己的成员

2. 实现运行时多态:虚函数与覆写

多态生效的关键是:基类中声明 virtual 函数,派生类中用 override 显式覆写,再通过基类指针或引用调用:

class Animal {protected:     std::string name; public:     Animal(const std::string& n) : name(n) {} 
virtual void speak() const {  // 声明为虚函数     std::cout << name << "makes a sound." << std::endl;}  virtual ~Animal() = default; // 建议虚析构函数 

};

立即学习 C++ 免费学习笔记(深入)”;

class Dog : public Animal {public: Dog(const std::string& n) : Animal(n) {}

void speak() const override {  // 覆写基类虚函数     std::cout << name << "says: Woof!" << std::endl;}

};

立即学习 C++ 免费学习笔记(深入)”;

class Cat : public Animal {public: Cat(const std::string& n) : Animal(n) {}

void speak() const override {     std::cout << name << "says: Meow!" << std::endl;}

};

3. 多态调用:指针与引用是关键

只有通过基类指针或引用调用虚函数,才能触发动态绑定。直接用对象调用仍是静态绑定:

  • 多态生效(推荐): Animal* p = new Dog("Max"); p->speak(); → 输出 Max says: Woof!
  • 多态生效(同样有效): Animal& r = dog_obj; r.speak();
  • 不触发多态(静态绑定): Dog d("Max"); d.speak(); → 编译期就确定调用 Dog::speak,和多态无关

4. 纯虚函数与抽象类

= 0 声明纯虚函数,含纯虚函数的类是抽象类,不能实例化,强制派生类实现该接口:

class Shape {public:     virtual double area() const = 0; // 纯虚函数     virtual ~Shape() = default;}; 

class Rectangle : public Shape {double w, h; public: Rectangle(double width, double height) : w(width), h(height) {} double area() const override {return w * h;} };

class Circle : public Shape {double r; public: Circle(double radius) : r(radius) {} double area() const override {return 3.1416 r r; } };

// 使用示例 std::vector> shapes; shapes.push_back(std::make_unique(5.0, 3.0)); shapes.push_back(std::make_unique(2.0));

for (const auto& s : shapes) {std::cout << "Area:" << s->area() << std::endl; // 多态调用}

text=ZqhQzanResources