使用类变量作为类成员函数的默认参数



我正在用C++构建一个LinkedList
addNode function:的签名

const bool LinkedList::addNode(int val, unsigned int pos = getSize());  

getSize()是一个公共的非静态成员函数:

int getSize() const { return size; }

size是一个非静态的私有成员变量
但是,我得到的错误是a nonstatic member reference must be relative to a specific object

如何实现此功能?

仅供参考,以下是整个代码:

#pragma once
class LinkedList {
int size = 1;
struct Node {
int ivar = 0;
Node* next = nullptr;
};
Node* rootNode = new Node();
Node* createNode(int ivar);
public:
LinkedList() = delete;
LinkedList(int val) {
rootNode->ivar = val;
}
decltype(size) getSize() const { return size; }
const bool addNode(int val, unsigned int pos = getSize());
const bool delNode(unsigned int pos);
~LinkedList() = default;
};

其他一些尝试包括:

const bool addNode(int val, unsigned int pos = [=] { return getSize(); } ());
const bool addNode(int val, unsigned int pos = [=] { return this->getSize(); } ());
const bool addNode(int val, unsigned int pos = this-> getSize());

我当前使用的当前解决方法:

const bool LinkedList::addNode(int val, unsigned int pos = -1) {
pos = pos == -1 ? getSize() : pos;
//whatever
}

默认参数是从调用方上下文提供的,它不知道应该绑定哪个对象进行调用。您可以添加另一个包装函数作为

// when specifying pos
const bool LinkedList::addNode(int val, unsigned int pos) {
pos = pos == -1 ? getSize() : pos;
//whatever
}
// when not specifying pos, using getSize() instead
const bool LinkedList::addNode(int val) {
return addNode(val, getSize());
}

最新更新