[英](C2352) C++ Return value as function default parameter
I'm making a linked list class and I want a convenient default argument for my 'remove()' function.我正在制作一个链接列表 class,我想要一个方便的默认参数用于我的“remove()”function。
int size() { return size_; }
int remove(int index = size() - 1);
^[C2352]
This gives me an error a call of a non-static member function requires an object , so I tried这给了我一个错误,调用非静态成员 function 需要 object ,所以我尝试了
int remove(int index = this->size() - 1);
However the this keyword cannot be used outside of a function.但是this关键字不能在 function 之外使用。 I want to avoid making size_ a public variable, for safety reasons.出于安全原因,我想避免将size_ 设为公共变量。 Note that my class is a template class.请注意,我的 class 是模板 class。
I would appreciate any help for finding a solution for this.对于找到解决方案的任何帮助,我将不胜感激。
Default arguments must be bound at compile time, so this
is not allowed since it's a runtime value.默认 arguments 必须在编译时绑定,因此this
是不允许的,因为它是运行时值。 You could use a free/static function but I don't see how the design is going to work as it wouldn't refer to any specific list instance.您可以使用免费/静态 function 但我不知道该设计将如何工作,因为它不会引用任何特定的列表实例。
In my opinion the best solution is to use a special value for what you need, eg:在我看来,最好的解决方案是为你需要的东西使用一个特殊的值,例如:
class List
{
static constexpr int LAST_ELEMENT_INDEX = -1;
void remove(int index = LAST_ELEMENT_INDEX)
{
if (index == LAST_ELEMENT_INDEX)
index = size() - 1;
..
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.