c++:举一个函数形参不能是引用的例子
巴扎黑
巴扎黑 2017-04-17 12:04:31
[C++讨论组]

这是一道习题

巴扎黑
巴扎黑

全部回复(3)
ringa_lee

还真不容易找到这样的例子。

不过,在肯定会修改实参内容,而这种修改又不能影响原变量的情况下,比较适合不用引用吧。

比如:

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);

在上面的例子中,第一个参数 path 是不是不用引用更好一些?

PHP中文网

hibernake说的是对的,我的例子不合适

迷茫

当使用非常量引用,而实参是字面值、表达式、需要转换的不同类型的对象时。如
void swap(int &a,int &b);
int a=2;
double b=3.0;
f(a,5);
f(a+2,a);
f(a,b);
都不行。也不能用const int&,因为要交换a与b的值。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号