【问题标题】:Overloading parentheses operator on vector in c++在 C++ 中重载向量上的括号运算符
【发布时间】:2018-01-20 10:00:57
【问题描述】:

我已尝试阅读此处的几个重载问题以了解如何做到这一点,但据我所知,重载括号与其他运算符不同,因为它需要在类中重载?

我的项目中有一个文件 main.cpp,我正在尝试重载 () 运算符,如下所示:

class vector<int> {
public:
    bool operator((iterator a);
};

具有匹配功能。

bool vector<int>::operator()(vector<int>::iterator a) {
    return (*a > 0);
}

但我遇到了几个错误,第一个是:

一个显式的特化必须在'template '类之前 向量 {

我试图纠正错误的要求,但似乎我对该过程的理解还不够好。

这里重载运算符的正确方法是什么?

提前感谢您的任何回复。

【问题讨论】:

标签: c++ vector operator-overloading parentheses


【解决方案1】:

您没有看错:operator()one of the four operators(以及 =[]-&gt;)只能作为类成员实现。由于std::vector 不是你的(无论是模板本身还是任何专门从它的类),你不能为它实现它们。

但仍有一个解决方案,那就是将std::vector 包装在您自己的类中,并为那个重载operator()

struct callableIntVector : std::vector<int> {
    using std::vector<int>::vector;

    bool operator ()(std::vector<int>::iterator a) const {
        return *a > 0;
    }
};

关于从标准容器继承的常见警告适用:不要以多态方式破坏它们,因为它们没有虚拟析构函数,注意不要对它们进行切片等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 2011-12-03
    • 2010-09-22
    • 1970-01-01
    • 2013-11-10
    • 2022-01-20
    • 2012-05-04
    • 1970-01-01
    相关资源
    最近更新 更多