我正在用 C++ 构建一个 LinkedList。addNode function
的签名:
const bool LinkedList::addNode(int val, unsigned int pos = getSize());
getSize()
是一个公共(public)的非静态成员函数:int getSize() const { return size; }
size
是一个非静态私有(private)成员变量。但是,我得到的错误是
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
}
最佳答案
默认参数是从调用方上下文提供的,它只是不知道应该绑定(bind)哪个对象被调用。您可以添加另一个包装函数
// 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());
}
关于c++ - 使用类变量作为类成员函数的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63297755/