【C++】面向对象的三大特性:封装、继承、多态(3)

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降级为privateprotected降级为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)

详见以上链接,点击蓝字。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值