1、面向对象的三大特性:封装、继承、多态——【C++】面向对象的三大特性:封装、继承、多态(1)
详见以上链接,点击蓝字。
2、C++的封装是如何实现的?——【C++】面向对象的三大特性:封装、继承、多态(2)
详见以上链接,点击蓝字。
3、C++的继承是如何实现的?
在C++中,继承是通过:(冒号)+访问控制修饰符(public、protected、private)实现的。
class 父类 {
// 父类的成员
};
class 子类 : 继承方式 父类 {
// 子类的成员
};
(1)继承方式
继承方式 | 父类的public成员在子类中的访问权限 | 父类的protected成员在子类中的访问权限 | 父类的private成员在子类中的访问权限 |
---|---|---|---|
public | 保持public | 保持protected | ❌ 无法访问 |
protected | 降级为protected | 保持protected | ❌ 无法访问 |
private | 降级为private | protected降级为private | ❌ 无法访问 |
class A {
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A {}; // `x` 变成 `public`,`y` 变成 `protected`
class C : protected A {}; // `x` 变成 `protected`,`y` 变成 `protected`
class D : private A {}; // `x` 变成 `private`,`y` 变成 `private`
(2)继承示例
#include <iostream>
using namespace std;
// 父类:Animal
class Animal {
public:
void eat() {
cout << "I can eat." << endl;
}
};
// 子类:Dog,继承 Animal
class Dog : public Animal {
public:
void bark() {
cout << "Woof! Woof!" << endl;
}
};
int main() {
Dog dog;
dog.eat(); // 继承自 Animal
dog.bark(); // 自己的方法
return 0;
}
输出:
I can eat.
Woof! Woof!
(3)构造函数与继承
子类不会继承父类的构造函数,但可以在子类的构造函数中调用父类的构造函数。
#include <iostream>
using namespace std;
class Person {
protected:
string name;
public:
Person(string n) { // 父类构造函数
name = n;
cout << "Person constructor called" << endl;
}
};
class Student : public Person {
private:
int studentID;
public:
// 子类构造函数调用父类构造函数
Student(string n, int id) : Person(n) {
studentID = id;
cout << "Student constructor called" << endl;
}
void showInfo() {
cout << "Name: " << name << ", ID: " << studentID << endl;
}
};
int main() {
Student s("Alice", 1001);
s.showInfo();
return 0;
}
输出:
Person constructor called
Student constructor called
Name: Alice, ID: 1001
分析:
-
Student继承Person,但Person没有默认构造函数,所以必须在子类构造函数中调用父类构造函数Person(n)。
-
子类的构造顺序:先调用父类Person的构造函数,再执行Student的构造函数。
(4)多层继承
C++支持多层继承,即一个子类可以继承另一个子类。
class Animal {
public:
void eat() { cout << "I can eat." << endl; }
};
class Mammal : public Animal {
public:
void breathe() { cout << "I can breathe." << endl; }
};
class Dog : public Mammal {
public:
void bark() { cout << "Woof! Woof!" << endl; }
};
int main() {
Dog dog;
dog.eat(); // 从 Animal 继承
dog.breathe(); // 从 Mammal 继承
dog.bark(); // Dog 自己的方法
}
4、C++的多态是如何实现的?——【C++】面向对象的三大特性:封装、继承、多态(4)
详见以上链接,点击蓝字。