dfs
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base::基类" << endl;
}
~Base()
{
cout << "调用基类的析构函数" << endl;
};
// 成员初始化列表语法
Base(string x,string y):x(x),y(y)
{
cout << "Base::传递参数的基类构造函数" << endl;
};
private:
string x;
string y;
};
class Derive:public Base // 派生 公有派生
// 使用公有派生,基类的公有成员将成为派生类的公有成员。
// 基类的私有部分也将成为派生类的一部分,但只能通过基类的公有和保护方法访问。
// 派生类不能直接访问基类的私有成员,而必须通过基类方法进行访问。
{
public:
Derive()
{
cout << "Derive::派生" << endl;
}
~Derive()
{
cout << "调用派生类的析构函数" << endl;
};
// 成员初始化列表语法
Derive(string z,string str2,string str3):Base(str2,str3),z(z)
{
//this.z = z;
cout << "Derive::传递参数的派生类的构造函数" << endl;
}
Derive(string z,const Base & base):Base(base),z(z)
{
cout << "Derive::传递参数的派生类的构造函数" << endl;
}
private:
string z;
};
int main()
{
// 基类对象应该在程序进入派生类构造函数之前被创建。
Derive *derive;
derive = new Derive("10","10","10");
delete derive;
cout << endl;
cout << "********************" << endl;
Base *base = new Base("20","20");
derive = new Derive("BG_80",*base);
//delete base;
// 派生类过期时,程序首先调用派生类的析构函数,然后调用基类的析构函数。
delete derive; // 这里要不要delete base? 应该不要
system("pause");
return 0;
}