请问bool test(string& testFileName) 和 bool test(string testFileName)有什么区别??

cd7809 2002-11-25 05:23:37

1: bool test(string& testFileName) 和 bool test(string testFileName)有什么
区别?

2: string test() 和 string& test()有什么区别??

谢谢!!
...全文
47 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
jian 2002-11-25
  • 打赏
  • 举报
回复
加上const可以确保在函数中,该参数不会被改变
这个优点有时候在规模比较大的程序中才能显示出来
skyfine 2002-11-25
  • 打赏
  • 举报
回复
基本的功能是一样的.但从可理解和可看性上来说&要比*更好懂一些.
比如
函数:
1.int swap(int *a,int *b){...};
2.int swap(int &a,int &b){...};
3.int swap(int a,int b){...};
调用:
...
1.swap(&m,&n);//传m,n的地址值
2.swap(m,n); //传m,n的引用.这样更容易理解些.
3.swap(m,n); //经常得到的结果是错误的.
而且由于引用值必须初始化,这样就避免了传送无效值.

cd7809 2002-11-25
  • 打赏
  • 举报
回复

非常感谢 NOldkiller:

那么bool test(string& testFileName) 和bool test(string* testFileName) 是一样的吗? 而且为什么经常用bool test(const string& testFileName)而不是bool test(const string* testFileName)呢??

NOldkiller 2002-11-25
  • 打赏
  • 举报
回复
1.在bool test(string& testFileName)中用到了引用参数,而引用实质上也是一种指针,这时在函数调用时,用的是引用传值方式,这时,不会发生string类的拷贝构造函数的调用,在test函数体中对testFileName的改变实际上就是对实参的改变.而bool test(string testFileName)则是传值调用,这时,会调用string的拷贝构造函数,且在test函数体中对形参所做的任何操作不会影响到实参的改变.
2. string test()
返回时会调用string的拷贝构造函数,这时返回值是一个临时对象,是不可以改变其值的.
而 string& test()则是返回值的左值.
如: 
 int g_Num = 5;
int& change(int nValue)
{
return nValue;
}

int Nochange(int nValue)
{
return nValue;
}

int main()
{
change(g_Num) = 10; //right
//这时g_Num的值就为10
NoChange(g_Num) = 20; //error
//会发生访问非法错误
  
return 0;
}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧