/*条款20:宁以 pass-by-reference to const 替换 pass by value */
#include<iostream>
#include<string>
using namespace std;
class Window{
public:
string name()const{
return "abc";
}
virtual void display()const{
cout << "Window::display()" << endl;
}
};
class WindowWithScrollBars :public Window{
public:
virtual void display()const{
cout << "WindowWithScrollBars::display()" << endl;
}
};
void printNameAndDisplay1(Window w){//对象切割 总是显示基类未重写版本,基类的构造函数被调用 子类的特化性质别切割掉了,仅仅留下基类对象
cout << w.name() << endl;
w.display();
}
void printNameAndDisplay2(const Window &w){//对象切割 总是显示基类未重写版本,基类的构造函数被调用 子类的特化性质别切割掉了,仅仅留下基类对象
cout << w.name() << endl;
w.display();
}
int main(){
WindowWithScrollBars w;
printNameAndDisplay1(w);
printNameAndDisplay2(w);
system("pause");
return 0;
}
/*另: 1传递引用一般比传递值高效,可避免切割问题
2以上规则并不适用于内置类型 以及STL的迭代器和函数对象 ,对它们而言值传递比较适当*/
条款20:宁以 pass-by-reference to const 替换 pass by value
最新推荐文章于 2022-07-13 17:31:21 发布