传引用相比于传值具有以下优点:
1.能够避免拷贝构造函数和临时对象的析构函数的调用开销;
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函数退出之前的函数调用情况
}