继承:是在已有的类上进行改造,产生一个新的类
对于继承的新的类,对于调用后的
#include<iostream>
using namespace std;
class A
{
public:
A(){
cout << "A::A()" << endl;
}
~A(){
cout << "A::~A()" << endl;
}
};
class B:public A
{
public:
B(){
cout << "B::B()" << endl;
}
~B(){
cout << "B::~B()" <<endl;
}
};
int main()
{
B n;
return 0;
}
产生的析构函数调用顺序如下所示:
父类先被构造,子类再被构造,析构时子类先退出,父类再退出。
#include<iostream>
using namespace std;
class A
{
public:
A(){
cout << "A::A()" << endl;
}
~A(){
cout << "A::~A()" << endl;
}
void print()
{
cout << "A::A()" << endl;
}
};
class B:public A
{
public:
B(){
cout << "B::B()" << endl;
}
~B(){
cout << "B::~B()" <<endl;
}
void print()
{
cout << "B::B()" << endl;
}
};
int main()
{
B n;
n.print();
return 0;
}
如果子类和父类里面函数名相同,子类会把父类的替换掉。