C++——关于继承的一些补充

一,关于切割

class Person1
{
public:
	void Print()
	{
		cout << "name:" << _name << endl;
		cout << "age:" << _age << endl;
	}
protected:
	string _name = "peter";//姓名
	int _age = 18;//年龄
};
class Student1 : public Person1
{
protected:
	int _stuid;
};
void main1()
{
	Student1 s;
	s.Print();
}
//基类和派生类的对象赋值转换
void main2()
{
	Student1 s;
	Person1 p = s;   //将子类中和父类相同的那一段切出来拷贝过去
	Person1& rp = s; //无隐式类型转换,无临时变量产生,这个引用是父类切出来那一部分的别名,注意是指向父类的,没有新对象产生
	Person1* pp = &s;//也是指向父类那一部分的指针,无对象产生

	Student1* ps = (Student1*)pp;
	ps->Print();
}

使用父类对象拷贝子类时,会将子类中父类继承下来的那部分内容切出来拷贝一份给父类,中间新对象产生,用父类引用或指针时没有新对象产生,父类指针或引用只代表了子类对象中从父类继承下来的那一部分,所以用父类指针或引用去改变值的时候,会改变子类的值

 二,继承下的默认成员函数调用补充

class Person3
{
public:
	Person3(const char* name = "peter")
		:_name(name)
	{
		cout << "Person()" << endl;
	}

	Person3(const Person3& p)
		:_name(p._name)
	{
		cout << "Person(const Person& p)" << endl;
	}

	Person3& operator=(const Person3& p)
	{
		cout << "Person& operator=(const Person& p)" << endl;
		if (this != &p)
			_name = p._name;
		return *this;
	}

	~Person3() {}
protected:
	string _name;
};
class Student3 : public Person3
{
public:
	Student3(const char* name = "张三", int num = 10)
		:Person3(name)
		, _num(num)
	{
		cout << "Student()" << endl;
	}

	Student3(const Student3& s)
		:Person3(s)
		,_num(s._num)
	{
		cout << "Student(const Student&)" << endl;
	}

	Student3& operator=(const Student3& s)
	{
		cout << "Student& operator=(const Student& s)" << endl;
		if (this != &s)
		{
			Person3::operator=(s);
			_num = s._num;
		}
		return *this;
	}

	//子类的析构函数跟父类的析构函数构成隐藏。
	//由于后面多态的需要,析构函数名字会被统一处理为destructtor()

	~Student3()
	{
		//Person::~Person();不需要显示调用,因为会自动调用
		// 不需要显示调用父类析构函数
		// 每个子类析构函数后面,会自动调用父类析构函数,这样才能保证先析构子类,再析构父类
		
		//...子类处理自己的
	}
	Student3* operator&()
	{
		return this;
	}
protected:
	int _num;
};
void main()
{
	Student3 s1; //子类调用父类和自己的构造
	Student3 s2(s1); //调用父类和子类的拷贝构造

	cout << "-----------------" << endl;

	Person3 p = s1; //切割,只调用父类的拷贝构造
	Student3 s3;
	s3 = s1;   //赋值,调用父类和子类的operator=()
}

 

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值