Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++继承

作者:只影天涯   发布日期:2026-04-14   浏览:57

// C++ 继承示例

#include <iostream>
using namespace std;

// 基类 (父类)
class Animal {
public:
    void breathe() {
        cout << "This animal breathes." << endl;
    }
};

// 派生类 (子类), 继承自 Animal
class Dog : public Animal {
public:
    void bark() {
        cout << "The dog barks." << endl;
    }
};

int main() {
    // 创建 Dog 类的对象
    Dog myDog;

    // 调用从 Animal 类继承的方法
    myDog.breathe();

    // 调用 Dog 类自己的方法
    myDog.bark();

    return 0;
}

解释说明:

  1. 基类(父类)Animal 是一个基类,它定义了所有动物共有的行为 breathe()
  2. 派生类(子类)Dog 是一个派生类,它继承自 Animal。通过使用 : public AnimalDog 继承了 Animal 的所有公共成员函数和变量。
  3. 继承的好处Dog 可以直接使用 Animal 中定义的 breathe() 方法,而不需要重新定义。同时,Dog 还可以定义自己特有的行为,如 bark()
  4. 对象创建与调用:在 main() 函数中,创建了一个 Dog 对象 myDog,并通过该对象调用了继承自 Animalbreathe() 方法以及 Dog 自己的 bark() 方法。

希望这个示例能帮助你理解 C++ 中的继承机制!

上一篇:c++ unordered_map

下一篇:c++多态

大家都在看

c++闭包

c++向上取整的代码

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++ functional

c++框架代码

c++格式化字符串

c++ orm框架

c++ string类

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站