继承就是我们写完一个类A后,又有一个需要描述的类B包括A中所有信息但还有别的信息的时候,我们就把B中和A联系起来,写成class B : public A这时只要写出比A多出的信息即可,但是实际使用还有A的所有内容。
下面我们写一个继承的例子来看一下实例化时的调用顺序
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
cout<<"Person()"<<endl;
}
~Person()
{
cout<<"~Person()"<<endl;
}
void eat()
{
cout<<"eat()"<<endl;
}
string m_strName;
int m_iAge;
};
class Worker : public Person
{
public:
Worker()
{
cout<<"Worker"<<endl;
}
~Worker()
{
cout<<"~Worker"<<endl;
}
void work()
{
cout<<"work()"<<endl;
}
int m_iSalary;
};
int main()
{
Worker *p=new Worker();
p->m_strName="jim";
p->m_iAge=20;
p->eat();
p->m_iSalary=1000;
p->work;
delete p;
p=NULL;
system("pause");
return 0;
}
运算结果如下
我们可以清晰地看到实例化时的调用顺序,我们调用的函数也成功了~
三种继承
公有继承:class B : public A
当B是公有继承A时,在public访问限定符下面的都在B内,B可以去调用A中的成员函数和数据成员,在这种继承中,B继承的A中的protected下的数据成员可以在B的成员函数中被引用,而A中private中的成员在B中不可见位置
继承public成员的程序参考上一段
继承protected成员的程序如下
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
cout<<"Person()"<<endl;
}
~Person()
{
cout<<"~Person()"<<endl;
}
void eat()
{
m_strName="jim";
m_iAge=20;
cout<<"eat()"<<endl;
}
protected:
string m_strName;
int m_iAge;
};
class Worker : public Person
{
public:
Worker()
{
cout<<"Worker"<<endl;
}
~Worker()
{
cout<<"~Worker"<<endl;
}
void work()
{
m_strName="marry";
cout<<"work()"<<endl;
}
int m_iSalary;
};
int main()
{
Worker work;
work.work();
system("pause");
return 0;
}
程序正常运行了
继承private成员的程序如下
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
cout<<"Person()"<<endl;
}
~Person()
{
cout<<"~Person()"<<endl;
}
void eat()
{
m_strName="jim";
m_iAge=20;
cout<<"eat()"<<endl;
}
private:
string m_strName;
int m_iAge;
};
class Worker : public Person
{
public:
Worker()
{
cout<<"Worker"<<endl;
}
~Worker()
{
cout<<"~Worker"<<endl;
}
void work()
{
m_strName="marry";
cout<<"work()"<<endl;
}
int m_iSalary;
};
int main()
{
Worker work;
work.work();
system("pause");
return 0;
}
程序报错:error C2248: 'm_strName' : cannot access private member declared in class 'Person'
程序保护继承:class A : protected B
私有继承: class A : private B