博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++默认参数不能是一个引用
阅读量:4681 次
发布时间:2019-06-09

本文共 1591 字,大约阅读时间需要 5 分钟。

引用做参数时不能传一个定值(如数字或者const等~~~)

 

somefunc(int& a = 4) -> default argument for ‘int& a’ has type ‘int’

Is there a solution for it that isn't playing with pointers?
My aim is to have a function that would take an int as a parameter by reference, but when no int is passed, a default int is given, but that default has to be by reference too - i don't know how to achieve it though.
You are asking for the impossible. Consider: no int is passed, so the default int value is used. The function modifies the value of the argument. Effectively, the default int value has changed! This is powerful, as it allows you to make the value of say, 0 become 1 (i.e., the int literal 0 becomes the int literal 1, meaning that 0 == 1 is true).
Perhaps you actually do not want to modify the argument, thus passing by value or const reference will do?
You can't take a reference of a constant, so if you did "somefunc(4)" with the above declaration (without the default) it would also fail. 
The reason to have a reference is that you will be able to modify the passed in variable. Since a constant can't be changed, it's kind of meaningless to pass in a constant as a reference, even if the compiler would allow it. 
We may be able to give you an option if you explain further what you actually are trying to achieve with this. 
One alternative is of course to declare two functions:
Code:
1
2
3
4
5
6
7
8
9
10
11
void
somefunc(
int
&a)
{
    
// this is called with one integer parameter.
   
...
}
 
void
somefunc()
{
   
// This is called when no parameter is given.
   
...
}

转载于:https://www.cnblogs.com/vanishfan/p/3314924.html

你可能感兴趣的文章
SYS_CONTEXT 详细用法
查看>>
Pycharm配置autopep8让Python代码更符合pep8规范
查看>>
函数的复写
查看>>
17_重入锁ReentrantLock
查看>>
winform窗口关闭提示
查看>>
64款工具,总有合适您的那款
查看>>
我的第一篇博客
查看>>
大数据学习线路整理
查看>>
【C++算法与数据结构学习笔记------单链表实现多项式】
查看>>
BZOJ 3224: Tyvj 1728 普通平衡树 or 洛谷 P3369 【模板】普通平衡树-Splay树模板题
查看>>
关于ProjectServer定制化项目中心页面
查看>>
【框架学习与探究之依赖注入--Autofac】
查看>>
requests
查看>>
windows下python3 python2 共存下安装virtualenvwrapper
查看>>
webservice学习教程(一):理论
查看>>
HTML,CSS的命名的习惯总结.
查看>>
call()、apply()、bind()
查看>>
Java常用工具类的使用
查看>>
Funcation:Object
查看>>
Repeater控件绑定SqlDataReader数据源
查看>>