簡體   English   中英

使用 class 變量作為 class 成員 function 的默認參數

[英]Using a class variable as a default argument to the class member function

我正在 C++ 中構建一個 LinkedList。
addNode function的簽名:

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

getSize()是一個公共的非靜態成員 function:

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
}

默認參數是從調用方上下文提供的,它只是不知道應該調用哪個 object。 您可以添加另一個包裝器 function 為

// 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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM