zoukankan      html  css  js  c++  java
  • 条款20.宁以pass-by-reference-to-const替换pass-by-vlaue

        缺省情况下c++以by value的方式传递对象至(或来自)函数。除非你另外指定,否则函数参数都是以实际实参的复件(副本)为初值,而调用端所获得的亦是函数返回值的一个复件。这些复件是由对象的copy构造函数产出,这可能使得pass-by-value成为昂贵的操作.

    #include "stdafx.h"
    #include <iostream>
    #include <string>

    class Window
    {
    public:
        std::string name() const;
        virtual void display() const
        {
            std::cout<<"windows display"<<std::endl;
        }
    };

    class WindowWithScrollBars:public Window
    {
    public:
        virtual void display() const
        {
            std::cout<<"WindowWithScrollBars display"<<std::endl;
        }
    };

    void show(Window w)
    {
        c.display();
    }

    void constshow(const Window &w)
    {
        c.display();
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
        WindowWithScrollBars good;
        show(good);//输出windowsdisplay
        constshow(good); //输出windowwithscrollbars display

        return 0;
    }

    注意show()传递的是value,而WindowWithScrollBars的所有特化信息都会被切除。不管你传递过来的对象原本是什么类型,参数w就像一个Window对象,因为他的类型是window.因为在show内调用的display调用的总是window::display,而绝不是widowWithScrollBars::display.

    解决这个切割的问题的办法,就是以by reference-to-const的方式传递w;

    也就是cosntshow看到的效果..如此这般,传入的是什么类型.他就是什么类型.因此pass-by-ference通常意味着真正传递的是指针。

  • 相关阅读:
    Log4Net 自定义级别,分别记录到不同的文件中
    带着忧伤,寻觅快乐
    程序员进阶学习书籍
    PHP编码技巧
    PHP精度问题
    Laravel5 构造器高级查询条件写法
    正则表达式 /i /g /m /ig /gi
    MySQL运算符的优先级
    PHP获取当前页面完整路径URL
    使用ssl模块配置同时支持http和https并存
  • 原文地址:https://www.cnblogs.com/crazycodehzp/p/3376304.html
Copyright © 2011-2022 走看看