// An highlighted block
#include<iostream>
#include<vector>
using namespace std;
int i = 0;
class A
{
public:
A()
{
cout << "父类构造函数" << endl;
}
A(int value) :a(value)
{
cout << "父类构造函数2" << endl;
}
void getchar()
{
cout << "调用父类函数" << endl;
}
virtual int getindex()
{
cout << a << endl;
return a;
}
~A()
{
cout << "父类析构函数" <<i++<< endl;
}
private :
int a =0;
};
class B :public A
{
public:
B()
{
cout << "子类构造函数" << endl;
}
void getchar()
{
cout << "调用子类函数" << endl;
}
virtual int getindex()
{
cout << "调用子类函数" << endl;
cout << b << endl;
return b;
}
~B()
{
cout << "子类析构函数" << endl;
}
private:
int b=1;
int a = 0;
};
int main()
{
A *a;
a = new B[2];
cout << "------" << endl;
cout << "------" << endl;
cout << "------" << endl;
a->getindex();
a->getchar();
delete []a;
system("pause");
return 0;
}
1,当基类指针指向派生类的时候,构造函数,会首先构造父类构造函数,再构造子类构造函数,而在析构时,只析构父类的析构函数,,
基类构造–》子类构造–》基类析构。
2,当派生类指针指向派生类的时,基类构造–》子类构造–》子类析构–》基类析构。
3,当基类指针指向派生类的时,如果类函数为是虚函数的时候,则访问派生类的函数,
如果类函数不是虚函数,则调用基类函数。