c++ - 方括号重载 => 没有运算符匹配操作数

标签 c++ templates operator-overloading brackets

我目前在重载自定义 vector 类中的方括号时遇到一些麻烦。

我的类基本上是这样的:

typedef uint32_t u32; // This is not actually here, but so you get the idea. Also, it is included in the problematic call's file

template<class T>
class JFFVector
{
public:
    //Init and stuff
    T& operator[](u32 iIndex)
    {
        return m_pData[iIndex + miDataOffset];
    }

private:
    T* m_pData;
    u32 m_iDataOffset;
}

在这个类函数中,我可以调用 (*this)[0] 并且一切正常。 现在我遇到的问题是一个具有如下成员的类:

class TOtherClass
{
public:
    // Stuff
    void DoSomething() const
    {
        for (u32 i; i < m_tItems.size(); ++i)
            m_tItems[i]->DoStuff(); // Which is a const function
    }

private:
    JFFVector<const JFFItem*> m_tItems;
}

问题是我的编译器在我面前抛出错误

no operator "[]" matches these operands

operand types are: const JFFVector[u32]

typedef uint32_t u32.

所以我注意到的一件事是,如果我将 m_tItems 设为一个指针,那么我可以执行“(*m_tItems)[i]->DoStuff()”并且它工作正常。但我不明白为什么它在非指针版本中不起作用。 (此外,我尝试使用简单的 int 而不是 u32,毫不奇怪,它没有用)

有人知道我做错了什么吗?而且,如果不是微不足道的,为什么它是错误的?

(很抱歉,如果这个问题已经得到解答,我尝试搜索类似的问题,但没有找到任何看起来像这个问题的东西)

最佳答案

有两个索引运算符可以重载——一个在 const JFFVector 上运行并返回一个 T const&,另一个在 JFFVector< 上运行 并返回一个 T&。您只实现了第二个。

您可以像这样实现它与非常量版本类似:

T const& operator[](u32 iIndex) const   // <-- note the two `const`s
{
    return m_pData[iIndex + miDataOffset];
}

请注意,此重载并非特定于 operator[],而是所有方法(可以由 const 或非 const 重载>).

在代码中需要 const 版本的原因是 DoSomething() 被声明为 const,因此 thisconst该方法中的 TOtherClass* 及其所有成员(尤其是此处的 m_tItems)在该方法中都是 const,因此只有 const 方法可以在它们上调用。由于没有为 m_tItems 定义 operator[]const 版本,编译器会给出该错误。

关于c++ - 方括号重载 => 没有运算符匹配操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40753575/

相关文章:

C++ 求解四次根(四阶多项式)

c++ - 模板实际上必须是编译时构造吗?

c++ - 递归泛型函数用作谓词,编译失败

c++ - 在类中使用带有重载算术运算符的ostream

c++ - 隐式转换为数组索引类型

C++ opencv获取编码的网络摄像头流

c++ - 在 C++ 中删除对象

c++ - Credential Providers V2 - 提交后添加代码并检查用户密码

c++ - 使用带有 std::unique_ptr 的模板时出现奇怪的链接器错误

c++ - 如何从类对象返回值?