(c++)继承

Ⅰ、继承中的对象模型

class father
{
private:
	int m_A;
	int m_B;
	int m_C;

};
class son:private father
{
private:
	int m_D;
};
void test01()
{
	cout << "son的内存空间:" << sizeof(son) << endl;
}

int main()
{test01();
	return 0;
}

输出是:16;

因为:类中一个整型和单精度变量,占四个字节,子类(1个)包含父类(3个)。

Ⅱ.同名成员处理

class father
{
public:
	int m_A = 10;
	void func()
	{
		cout << "father的成员函数" << endl;
	}
	
};
class son :public father
{
public:
	int m_A = 20;
	void func()
	{
		cout << "son的成员函数" << endl;
	}
};
void test01()
{//相同的成员处理;
	son s1;
	cout << "son的成员:" << s1.m_A << endl;
	cout << "father的成员:" << s1.father::m_A << endl;
}
void test02()
{//相同成员函数的处理;
	son s2;
	s2.func();
	//如果子类出现了和父类一样的成员函数,
	// 编译器就会把父类的成员函数隐藏;
	s2.father::func();
	

}

其中,注意,访问父类成员的表达方式:(子类创建的对象名).(父类对象名)::(要访问的东西)s1.father::(....)

 Ⅲ.同名静态成员处理

与同名成员处理的方式一样,只不过,访问的方式不同;

注意:静态成员的表现形式,静态变量是类内声明,类外初始化;

class father
{
public:
	static int m_A;
	static void func()
	{
		cout << "father-static" << endl;
	}
};  int father::m_A = 10;
class son:public father
{
public:
	static int m_A;
	static void func()
	{
		cout << "son-static" << endl;
	}
}; int son::m_A = 10;
// 1.通过对象访问。
void test01()
{
	cout << "通过对象访问:" << endl;
	son s1;
	cout << "son-m.A=" << s1.m_A << endl;
	s1.func();
	cout << "father-m.A=" << s1.father::m_A << endl;
	s1.father::func();
}
// 2.通过类名直接访问;
void test02()
{
	cout << "通过类名直接访问:" << endl;
	cout << "son-m.A=" <<son::m_A << endl;
	son::func();
	cout << "father-m.A=" << son::father::m_A << endl;
	son::father::func();
//第一个::代表通过类名方式访问,第二个::代表访问父类作用域下;
}

Ⅳ.菱形继承问题

在没有用virtual时,可以分别给sheep,tuo,两个类中的m_A赋值,而sheeptuo无法确定它的年龄。

结果为:

但是用virtual后:

class animal
{
public:
	animal()
	{
		m_A = 10;
	}
	int m_A;
};
//利用虚继承。
class sheep:virtual public animal
{};
class tuo :virtual public animal
{};
class sheeptuo :public sheep, public tuo
{};
void test01()
{
	sheeptuo p1;
	p1.sheep::m_A = 10;
	p1.tuo::m_A = 19;
	cout << "p1.sheep::m_A: " << p1.sheep::m_A << endl;
	cout << "p1.tuo::m_A:" << p1.tuo::m_A << endl;
	cout << "p1.m_A:" << p1.m_A << endl;

}

三个类的m_A的结果都相同:

 注:自己跟着黑马学的,总结一下。有不足,希望指出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值