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

标签 c++ function class static default-value

我正在用 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/

相关文章:

javascript - "$.______ is not a function"错误。怎么了?

Javascript:在函数完成时调用特定函数

javascript - 如何使用 "this"关键字来调用

c++ - 为另一个类中的类型重载 <<

c++ - 字节大小(说明)

C++ boost 线程问题

c++ - 在 for 循环中,就迭代总数而言,循环控制变量的前/后递增之间是否存在差异?

c++ - 如何保持 QSlider 处于激活状态以允许随时使用箭头移动

ios - 如何在 Swift 中设置新的类文件

class - 带 `min` 的类型类?