zoukankan      html  css  js  c++  java
  • Cpp Chapter 8: Adventures in Functions Part2

    ) You can't pass an expression to a function that requires a reference:

    double refcube(double &ra);
    double x = 3.0;
    refcube(x); // valid
    refcube(x + 3.0) // invalid because x + 3.0 is not a variable

    ) Passing by value is a norm that you might not want to change the origin value while doing calculations(e.g. calculating the square of a number). If you insist on using a reference while not changing the original value, use const in function prototype and header:

    double refcube(const double &ra)

    ) Better use const reference arguments because const reference allows the function to handle both const and non-const data, However, non-const reference could only handle non-const data.

    ) Using references with a structure(most intended):

    struct thing
    {
    ...
    };
    
    void process(thing & rt); // accept struct as reference
    void process(const thing & rt); // accept struct as const reference

    You could also make a function return a reference to structure, this makes the return process easier, without copying the entire structure again:

    struct thing
    {
    ...
    };
    
    const thing & process(const thing & rt); // return a const struct reference
    const thing & accumulate(thing & target, const thing & addition);
    thing a, b, c, total;
    total = accumulate(accumulate(a, b), c);
    // return struct reference makes it possible to nest accumulate() function
    // also make it easier for the return value to go straight to total
    // instead of copy the entire structure again

    Also avoid returning references to temporary structures which are declared inside a function(also better const reference).

    const string & version(string & s1, const string & s2);
    
    const string & version(string & s1, const string & s2)
    {
        string temp; // local variable
        temp = s2 + s1 + s2;
        return temp; // Don't return reference to local variables!!!!!
    }
  • 相关阅读:
    开源作品-PHP写的Redis管理工具(单文件绿色版)-SuRedisAdmin_PHP_1_0
    开源作品-PHP写的JS和CSS文件压缩利器(单文件绿色版)-SuMinify_PHP_1_5
    Javascript关于JSON集合的几种循环方法
    正式安家
    Oracle 常用脚本
    Centos6安装zabbix_server
    centos_6下源码编译安装zabbix之一 LNMP环境的搭建
    reg51.h
    C语言浮点数存储结构分析
    WinForm程序中两份mdf文件问题的解决
  • 原文地址:https://www.cnblogs.com/fsbblogs/p/9693116.html
Copyright © 2011-2022 走看看