是否更正C++列表类重载"()"getter和setter的签名
Correct signature for overloading `()` getter and setter for C++ list class?
我正在创建一个自定义的double
列表类。我想重载()
运算符,这样我既可以访问元素,也可以为列表元素赋值。这些函数分别以返回类型double
和double &
出现在下面的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
相关文章:
- 如何通过 getter 函数删除矢量的元素?
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 如何为 C 型字符串数组编写 getter 和 setter?
- C++ Setter/Getter,cout 工作,printf 失败
- 指向成员函数的模板指针 - getter
- 使用 getter 访问成员变量C++
- 如何在节点插件中创建 getter?
- 即使有 0 个错误,Getter 似乎也会使程序崩溃
- 将值推送到 getter 函数调用的列表中时出现问题
- 为什么我的编译器在调用 const getter 函数时抛出"转换丢失(const)限定符"错误?
- 私有变量无法正常工作的C++getter方法(只有Java经验)
- 如何使用 getter 功能push_back列表?
- 常量和非常量 getter 具有相同的名称
- 不一定获得成员价值的 getter 方法?
- 在 c++ 中使用 getter 作为unordered_map会创建大小为 8 的无效读取
- Getter 和 Setter 用于类 C++ 中的数组元素
- 无法使用在子类中定义的虚拟getter实现基类
- 如何编写C++getter和setter
- 如何为包含另一个类实例的数组制作常量 getter?
- 为什么叮当格式在 getter 的大括号之前不会中断?