关于派生类到基类的向上类型转换

1.可以直接将派生对象 赋值给 基类变量

2.可以 将派生对象的指针 直接 给到 基类指针变量 

3.可以直接将派生对象直接给到 基类的 引用

#include<iostream>
#include<string>
using namespace std;

class Base
{
protected:
	int x;
public:
	Base(int x_ = 0) :x(x_) {
		cout << "调用基类1个参数的构造函数" << endl;
	};
	//getX
	int getX()
	{
		return x;
	}
};
//派生类
class Derived:public Base
{
private:
	int y;
public:
	using Base::x;  //修改x的访问权限为public
	Derived(int y_ = 0,int x_=999) :y(y_) {
		this->x = x_;
		cout << "调用派生类1个参数的构造函数" << endl;
	};
};

int main()
{
	//测试:
	Base test_base;
	Derived test_derived;
	//(1)通过 将派生对象 赋值给 基类对象 实现向上类型转换的值传递
	cout << "原来 test_base中的x的值: " << test_base.getX() << endl;
	test_base = test_derived;
	cout << "后来test_base中的x的值: " << test_base.getX() << endl;
	//成功赋值
	//(2)将派生类对象的地址给到基类指针
	Base* base_p = new Base(555);
	cout << "原来 test_p中的x的值: " << base_p->getX() << endl;
	base_p = &test_derived;
	cout << "后来 test_p中的x的值: " << base_p->getX() << endl;
	//成功赋值
	//(3)将派生对象 赋值给 基类的引用类型变量
	Base & base_r = test_derived;
	cout << "原来 base_r中的x的值: " << base_r.getX() << endl;
	//赋值成功
	//(4)将开辟的derived类型的指针直接传递给 base指针
	base_p = new Derived(520); //这个值给到了y...
	cout << "最后 test_p中的x的值: " << base_p->getX() << endl;

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值