为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
Why I need to define a default reference parameter as const so that I can assign a lvalue to it?
>我用默认参数定义了一个函数:
void resize(size_t n, std::string &s = std::string()); // error: initial value to non-const must be lvalue
正确的方式:
void resize(size_t n, const std::string &s = std::string());
我想知道为什么const
会有所作为?
我知道可以为const
变量分配一个左值。他们是同一个问题吗?
const int a = 42;
添加重载。这是一个最简单、最容易解决的方法。
void resize(size_t n, std::string &s);
//add overload
void resize(size_t n)
{
std::string s;
resize(n, s);
}
相关文章:
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- C++为 void 指针分配一个字符串
- 有没有办法在同名类 (c++) 中为对象分配一个指针变量
- 获取指针的地址会为其分配一个值
- 在C++中分配一个大内存块
- 是否可以在专用内存空间中分配一个为提升管理共享内存而创建的对象
- 为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
- 为无符号字符* 分配一个数字
- 分配一个(固定大小)矢量<矢量<double>>以便高效访问并添加它们?
- 如何异步销毁对象并立即分配一个新对象
- 如何在while循环之外分配一个新值
- 如何在堆上分配一个void*阵列
- 映射和设置总是一次分配一个项目吗
- 在对象数组C 中分配一个对象
- 动态数组仅分配一个元素
- 在为其分配一个新值之前,应将`nullptr`分配给`sTD :: simelod_ptr`
- 如果我在C++中分配一个带有运算符 new[] 的对象数组,但单独释放它们是否仍然构成内存泄漏
- C - 分配一个未签名的炭缓冲区,然后用字符串填充
- 为什么reverse_iterator无法使用forward Itererator分配一个新值
- C++ 我可以使用字符串::at分配一个整数吗?