在C++中,面向对象编程的核心概念之一是“继承”,它允许我们根据已有的类创建新的类。
新的类继承并可以使用现有类的所有属性和方法,同时还可以定义自己的新属性和方法。这就是所谓的“派生”。
下面是一个简单的例子,我们将定义一个基类Animal
,并从这个基类派生出两个子类Dog
和Cat
。
// 基类 Animal
class Animal {
public:
// 基类的构造函数
Animal() {
cout << "Animal 对象被创建。" << endl;
}
// 基类的析构函数
~Animal() {
cout << "Animal 对象被销毁。" << endl;
}
// 基类的公有方法
void eat() {
cout << "Animal is eating." << endl;
}
// 基类的受保护成员变量
protected:
string name;
};
// Dog 类从 Animal 类派生
class Dog : public Animal {
public:
// Dog 类的构造函数
Dog() {
name = "Dog";
cout << "Dog 对象被创建。" << endl;
}
// Dog 类的析构函数
~Dog() {
cout << "Dog 对象被销毁。" << endl;
}
// Dog 类的特有方法
void bark() {
cout << "Dog is barking." << endl;
}
};
// Cat 类从 Animal 类派生
class Cat : public Animal {
public:
// Cat 类的构造函数
Cat() {
name = "Cat";
cout << "Cat 对象被创建。" << endl;
}
// Cat 类的析构函数
~Cat() {
cout << "Cat 对象被销毁。" << endl;
}
// Cat 类的特有方法
void meow() {
cout << "Cat is meowing." << endl;
}
};
int main() {
// 创建 Dog 对象
Dog myDog;
myDog.eat(); // 继承自 Animal 类的方法
myDog.bark(); // Dog 类的特有方法
// 创建 Cat 对象
Cat myCat;
myCat.eat(); // 继承自 Animal 类的方法
myCat.meow(); // Cat 类的特有方法
return 0;
}
在上述代码中:
Animal
是基类,它有一个公有方法eat()
和一个受保护的成员变量name
。Dog
和Cat
是从Animal
类派生的子类,它们都继承了Animal
类的所有公有和保护成员。Dog
类添加了一个特有的公有方法bark()
。Cat
类添加了一个特有的公有方法meow()
。
在 main()
函数中,我们创建了一个 Dog
对象和一个 Cat
对象,并调用了它们的公有方法。你会看到,Dog
和 Cat
对象都可以调用从 Animal
类继承的 eat()
方法,同时也可以调用它们自己特有的方法。
这就是C++中的继承与派生的基本概念。需要注意的是,除了公有继承(public
)外,C++还支持私有继承(private
)和保护继承(protected
),这些继承方式有不同的访问规则,需要根据具体的需求来选择。