C++继承

继承就是我们写完一个类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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值