search

Home  >  Q&A  >  body text

c++:举一个函数形参不能是引用的例子

这是一道习题

巴扎黑巴扎黑2809 days ago790

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 12:06:31

    It’s really hard to find such examples.

    However, when the actual parameter content will definitely be modified, and this modification cannot affect the original variable, it is more suitable not to quote it.

    For example:

    bool read_file_in(string path, const string &file, string &out)
    {
        path += "/" + file;
        
        return read_file(path, out);
    }
    
    bool write_file_in(string path, const string &file, const string &in)
    {
        path += "/" + file;
        
        return write_file(path, in);
    }
    
    //...
    
    string path, data;
    
    //...
    read_file_in(path, "in.txt", data);
    write_file_in(path, "out.txt", data);
    

    In the above example, is it better not to use a reference for the first parameter path?

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 12:06:31

    What hibernake said is right, my example is inappropriate

    reply
    0
  • 迷茫

    迷茫2017-04-17 12:06:31

    When using non-const references and the actual parameters are literal values, expressions, or objects of different types that need to be converted. Such as
    void swap(int &a,int &b);
    int a=2;
    double b=3.0;
    f(a,5);
    f(a+2,a );
    f(a,b);
    will not work. You can't use const int& either, because the values ​​of a and b need to be exchanged.

    reply
    0
  • Cancelreply