是否更正C++列表类重载"()"getter和setter的签名

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

本文关键字:quot getter setter 列表 重载 是否 C++      更新时间:2023-10-16

我正在创建一个自定义的double列表类。我想重载()运算符,这样我既可以访问元素,也可以为列表元素赋值。这些函数分别以返回类型doubledouble &出现在下面的list.h中。但是,您可以在下面看到,当我运行main.cpp并尝试同时使用两者时,只调用了第二个operator()。我显然误解了一些东西——我当前的代码中有什么不正确,为什么不正确?

list.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];
}

main.cpp

#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