继承以及析构,构造函数过程
继承
实例代码
#ifndef _HERO_H
#define _HERO_H
#include <iostream>
using namespace std;
class hero
{
public:
hero();
hero(const string &name);
~hero();
hero(const hero&other);
void showskill();
void heroname();
private:
string name;
};
#endif
#include <iostream>
#include "hero.hpp"
using namespace std;
hero::hero() : name("NULL")
{
cout << "默认构造函数" << endl;
}
hero::hero(const string &name) : name(name)
{
cout << "全參构造函数" <<endl;
}
hero::~hero()
{
cout << "析构函数" << endl;
}
hero::hero(const hero&other) : name(other.name)
{
cout << "拷贝构造函数" <<endl;
}
void hero::showskill()
{
cout << "飞天" <<endl;
}
void hero::heroname()
{
cout << "hero_name " << name << endl;
}
#ifndef _MONKEYKING_HPP
#define _MONKEYKING_HPP
#include <iostream>
#include "hero.hpp"
using namespace std;
class monkeyking : public hero
{
public:
monkeyking();
~monkeyking();
void showskill();
void showweapon();
private:
string weapon;
};
#endif
#include "monkeyking.hpp"
#include <iostream>
using namespace std;
monkeyking::monkeyking() : hero("悟空"),weapon("棒子")//继承了基类的名字,在参数列表当中进行初始化
{//名字是基类的成员变量,只能通过成员函数构造函数进行初始化,如果是protected的话可以直接对成员数据初始化
cout << "childern Default constructor" << endl;
}
monkeyking::~monkeyking()
{
cout << "childern Destructor" <<endl;
}
void monkeyking::showskill()//重写了基类的公有成员函数,隐藏了基类的成员函数
{
cout << "火眼" << endl;
}
void monkeyking::showweapon()
{
cout << weapon <<endl;
}
#include "monkeyking.hpp"
int main(int argc, const char *argv[])
{
hero h;
h.showskill();
h.heroname();
cout << "-----------" <<endl;
monkeyking mk;
mk.showskill();
mk.heroname();
mk.showweapon();
cout << "-----------" << endl;
hero h1 = mk;
cout << &mk << endl;
cout << sizeof(mk) << endl;
cout << &h1 << endl;
hero h2 = h1;
cout << &h1 << endl;
cout << &h2 << endl;
return 0;
}
## 运行结果
构造函数以及析构函数过程
#include <iostream>
using namespace std;
class A
{
public:
A(){
cout << "A default constructor" << endl;
}
A(int){
cout << "A argument constructor" << endl;
}
~A(){
cout << "A destructor" << endl;
}
private:
};
class B
{
public:
B(){
cout << "B default constructor" << endl;
}
B(int){
cout << "B argument constructor" << endl;
}
~B(){
cout << "B destructor" << endl;
}
private:
};
class C : public A , public B
{
public:
#if 1
C() : a2(10),A(),B(),b(),a1()
{//先初始化基类的成员变量,再初始化自己成员数据变量
cout << "C default constructor" << endl;
}
#endif
#if 0
C()
{
cout << "C default constructor" << endl;
}
#endif
C(int){
cout << "C argument constructor" << endl;
}
~C(){
cout << "C destructor" << endl;
}
private:
A a1;//
B b;
A a2;
static A a3;
};
int main(int argc, const char *argv[])
{
C c;
cout << "------" << endl;
return 0;
}