// C++ 类继承示例
#include <iostream>
using namespace std;
// 基类 (Base Class)
class Animal {
public:
void breathe() {
cout << "This animal breathes." << endl;
}
};
// 派生类 (Derived Class), 继承自 Animal
class Dog : public Animal {
public:
void bark() {
cout << "The dog barks." << endl;
}
};
int main() {
Dog myDog;
// 调用从基类继承的方法
myDog.breathe(); // 输出: This animal breathes.
// 调用派生类自己的方法
myDog.bark(); // 输出: The dog barks.
return 0;
}
Animal:定义了一个公共方法 breathe(),表示动物呼吸的行为。Dog:通过 public 关键字继承自 Animal 类。除了继承了 Animal 的所有公共成员外,还定义了自己的方法 bark()。main 函数中,创建了一个 Dog 类的对象 myDog,并通过该对象调用了从基类继承的方法 breathe() 和派生类自己的方法 bark()。这个例子展示了如何使用 C++ 中的类继承机制来实现代码复用和扩展功能。
上一篇:c++序列化
下一篇:c++ ascii
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站