派生类
定义:
派生类成员是指除了从基类继承的所有成员之外,新增加的数据和函数成员
派生类生成过程:
访问控制:
类型兼容规则(必须有继承关系)
- 实现基类的复制构造函数
- 实现派生类的复制构造
- 实现派生类调用基类
首先会调用基类的构造函数其次在实现派生类的构造函数,而析构函数函数的调用顺序刚好与构造函数相反,先执行派生类的析构函数最后实现基类的析构函数。#include <iostream> #include <cstring> using namespace std; class Base { public: Base(int n):m_i(n) { cout<<"Base::Base()"<<endl; } ~Base() { cout<<"Base::~Base()"<<endl; } private: int m_i; }; class Derived : public Base { public: Derived(int a,int b ):Base(b),m_k(a) { cout<<"Derived()"<<endl; } ~Derived() { cout<<"~Derived()"<<endl; } private: int m_k; }; int main() { Derived d(10,20); return 0; }
-
基类指针指向派生类
派生类可以调取到基类函数的相关数据(体现了就近原则会先调用基类自己的相关函数数据),但是基类不一定能调取到派生类的数据,如时钟习题,但是也存在调取可能如下列代码运用到了隐函数#include <iostream> using namespace std; // 基类 class Base { public: virtual void show() { cout << "Base show()" << endl; } virtual ~Base() {} // }; // 派生类 class Derived : public Base { public: void show() override { // 使用override关键字明确表明这是一个重函数 cout << "Derived show()" << endl; } }; int main() { // 派生类对象 Derived d; // 基类指针指向派生类对象 Base* basePtr = &d; // 通过基类指针调用虚函数,执行的是派生类中的版本 basePtr->show(); // 输出: Derived show() return 0; }
🙋♂️练习:从时分秒的到年月日时分秒的实现
其中运用到了 基类指针指向派生类,体现就近原则所以只打印了基类函数中存在的时分秒
#include <iostream>
using namespace std;
class Clock
{
public:
Clock(int h, int m, int s) : hour(h), minute(m), second(s)
{
cout << "Clock(int, int, int)" << endl;
}
Clock(const Clock &other) : hour(other.hour), minute(other.minute), second(other.second)
{
cout << "Clock(Clock &)" << endl;
}
~Clock()
{
cout << "~Clock()" << endl;
}
void setTime(int h, int m, int s) //this
{
this->hour = h;
minute = m;
second = s;
}
void showTime() const// const Clock *this
{
cout << this->hour << ":" << this->minute << ":" << this->second << endl;
}
protected:
int hour;
int minute;
int second;
};
class CalendarClock : public Clock
{
public:
CalendarClock(int y,int M,int d,int h,int m,int s):Clock(h,m,s),year(y),month(M),day(d)
{
cout <<"CalendarClock::()"<<endl;
}
CalendarClock(const CalendarClock &other):Clock(other),year(other.year),month(other.month),day(other.month)
{
cout<<"CalendarClock (CalenderClock &)"<<endl;
}
~CalendarClock()
{
cout<<"CalenderClock~"<<endl;
}
void setTime(int y,int M,int d,int h,int m,int s)
{
year = y;
month = M;
day = d;
Clock::setTime(h,m,s);
// hour = h;
// minute = m;
// second = s;
}
void showTime() const
{
cout<<year<<"-"<<month<<"-"<<day<<"-"<<hour<<":"<<minute<<":"<<second<<":"<<endl;
//Clock::setTime();
}
private:
int year;
int month;
int day;
};
int main()
{
CalendarClock c(2024,8,9,10,38,21);
c.showTime();
//基类指针指向派生类指针
Clock *p = &c;
p->showTime();
//c.show();
}