c++:举一个函数形参不能是引用的例子
巴扎黑
巴扎黑 2017-04-17 12:04:31
0
3
785

这是一道习题

巴扎黑
巴扎黑

reply all(3)
左手右手慢动作

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?

洪涛

What hibernake said is right, my example is inappropriate

迷茫

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template