简体   繁体   中英

(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.

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

int remove(int index = this->size() - 1);

However the this keyword cannot be used outside of a function. I want to avoid making size_ a public variable, for safety reasons. Note that my class is a template 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. 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.

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;

    ..
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM