簡體   English   中英

為 C++ 列表類重載 `()` getter 和 setter 的正確簽名?

[英]Correct signature for overloading `()` getter and setter for C++ list class?

我正在創建一個自定義的double列表類。 我想重載()運算符,以便我可以訪問元素並將值分配給列表元素。 這些函數分別以返回類型doubledouble &出現在list.h 但是,當我運行main.cpp時,您可以在下面看到,嘗試同時使用兩者,只有第二個operator()被調用。 我顯然誤解了一些東西——我當前的代碼有什么不正確,為什么不正確?

列表.h

#include <iostream>

class list {
    public:
        // Constructor
        list(int length);
        // Destructor
        ~list();
        // Element accessors
        double operator()(int i) const;
        double & operator()(int i);
    private:
        int length;
        double * data;
};

list::list(int length) {
    this->length = length;
    this->data   = new double[length];
}

list::~list() { delete [] this->data; }

double list::operator()(int i) const {
    std::cout << "()1" << std::endl;
    return this->data[i];
}

double & list::operator()(int i) {
    std::cout << "()2" << std::endl;
    return this->data[i];
}

主程序

#include <iostream>
#include "list.h"
using namespace std;

int main() {
    list l(3);
    double x;

    // Assign to list element. Should print "()2".
    l(1) = 3;
    // Get list element value. Should print "()1".
    x = l(1);

    return 0;
}

編譯后,程序打印:

()2
()2

編輯

我的問題是由於我添加這兩個函數的順序以及我的一些誤解引起的。 我首先寫了一個簡單的訪問器,即:

double list::operator()(int i);

之后,我嘗試添加一個“setter”重載:

double & list::operator()(int i);

此時編譯器抱怨。 我在網上搜索,並沒有真正理解,在第一個函數后添加了一個const關鍵字。 這停止了​​編譯器的抱怨,但隨后導致了上述問題。 我的解決方案是消除第一個重載,即刪除:

double operator()(int i) const;
list l(3);

這是list類的非常量實例。 調用operator()函數時,將使用非常量重載。

const_cast<const list&>(l)(3); // Explicitly call the const overload

暫無
暫無

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

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