传值与传引用

传引用相比于传值具有以下优点:
1.能够避免拷贝构造函数和临时对象的析构函数的调用开销;

2.能够避免将派生类对象传递给基类形参时产生的切割现象,切割现象会将派生类所具有的特性都切割掉,变成一个简单的基类对象。

#include<iostream>
using namespace std;
class Base{
	public:
		Base(){}
		virtual void display(){
			cout<<"Base::display()"<<endl;
		}
		Base(const Base& rhy){
			cout<<"Base::Base(const Base& rhy)"<<endl;
		}
		virtual ~Base(){
			cout<<"Base::~Base()"<<endl;
		}
};
class Derived:public Base{
	public:
		Derived():Base(){}
		void display() override{
			cout<<"Derived::display()"<<endl;
		}
		Derived(const Derived& rhy):Base(rhy){
			cout<<"Derived::Derived(const Derived& rhy)"<<endl;
		}
		~Derived(){
			cout<<"Derived::~Derived()"<<endl;
		} 
};
Base function(Base demo){
	demo.display();
	return demo;
}
Base& function2(Base& demo){
	demo.display();
	return demo;
}
int main(){
	Derived derived;
	cout<<"传值下的函数调用与切割现象"<<endl; 
	function(derived);
	cout<<"传引用下的函数调用,无切割现象"<<endl;
	function2(derived);
	system("pause");//观察main函数退出之前的函数调用情况 
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值