继承
1,继承的好处:可以减少重复的代码
派生类里面的成员,包含两部分:
a,一类是从基类中继承过来的,一类是自己增加的成员。
b,从基类继承过来的表现其共性,而新增的成员体现其个性。
2,继承方式有三种
a,public 父类:继承下来的都可以访问
b,protected 父类:继承过后子类中的继承全部变为protected
c,private 父类:继承过后子类中的继承全部变为private.
注意子类只能访问父类中的public和protected,不能访问private权限
eg:
#include<iostream>
using namespace std;
class common
{
public:
void show()
{
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
cout<<"c="<<b<<endl;
}
common()
{
this->a=10;
this->b=18;
this->c=20;
}
public:
int a;
int b;
protected:
int c;
private:
int d;
};
class person:public common
{
public:
void showperson()
{
cout<<"public"<<endl;
}
};
class person1:protected common
{
public:
void showperson1()
{
cout<<"protected"<<endl;
}
int getB()
{
return b;
}
};
class person2:private common
{
public:
void showperson2()
{
cout<<"private"<<endl;
}
};
void test01()
{
person acy;
acy.showperson();
cout<<"acy:"<<acy.b<<endl;
}
void test02()
{
person1 bat;
bat.showperson1();
cout<<"bat:"<<bat.getB()<<endl;
}
void test03()
{
person2 yan;
yan.showperson2();
}
int main()
{
test01();
test02();
test03();
return 0;
}
3,子类中的析构与构造的顺序
构造由外到内,析构由内到外
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"father"<<endl;
}
~Base()
{
cout<<"father des"<<endl;
}
};
class son:public Base
{
public:
son()
{
cout<<"son"<<endl;
}
~son()
{
cout<<"son des"<<endl;
}
};
int main()
{
son a;
return 0;
}
结果
4,继承同名成员处理
a,访问子类同名成员 直接访问即可
b,访问父类同名成员 直接加作用域
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"father"<<endl;
}
~Base()
{
cout<<"father des"<<endl;
}
void func()
{
cout<<"func1"<<endl;
}
void func(int age)
{
cout<<"func1"<<endl;
}
int age;
};
class son:public Base
{
public:
son()
{
cout<<"son"<<endl;
}
~son()
{
cout<<"son des"<<endl;
}
void func()
{
cout<<"func"<<endl;
}
int age;
};
int main()
{
son a;
a.age=100;
a.Base::age=200;
a.func();
a.Base::func();
a.Base::func(100);
return 0;
}
5,继承同名静态成员处理方式
和非静态处理是一样的
#include<iostream>
using namespace std;
class Base
{
public:
static void test()
{
cout<<"this is father's test"<<endl;
}
public:
static int m_Age;
};
int Base::m_Age=100;
class son:public Base
{
public:
static int m_Age;
static void test()
{
cout<<"this is son's test"<<endl;
}
};
int son::m_Age=200;
void test01()
{
son a;
cout<<a.Base::m_Age<<endl;
cout<<a.m_Age<<endl;
a.Base::test();
a.test();
cout<<son::Base::m_Age<<endl;
cout<<son::m_Age<<endl;
son::test();
}
int main()
{
test01();
return 0;
}
6,菱形继承
概念:两个派生类继承同一个基类,又有某个类同时继承者两个派生类,这种继承叫做菱形继承。
virtual:在父类前面加上代表虚基类,孙子派生类在继承时只是会继承相同类型的一个数据继承的是一个指针,主要是节约空间
#include<iostream>
using namespace std;
class animal
{
public:
animal()
{
m_Age=18;
}
int m_Age;
};
class sheep:virtual public animal
{
};
class camel:virtual public animal
{
};
class sheepCamel:public sheep,public camel
{
};
int main()
{
sheepCamel a;
cout<<a.camel::m_Age<<endl;
cout<<a.sheep::m_Age<<endl;
cout<<a.m_Age<<endl;
return 0;
}