c++ - "error: expected unqualified-id before ' float ' "用于 operator[] 重载

标签 c++ overloading operator-keyword

我试图为我的一个容器实现 operator[]。但是我真的是 c++ 的新手,我的实现似乎有错误。

我这样声明它们:

float& operator[](const int &idx);
const float& operator[](const int &idx) const;

应该没问题,它几乎是从教程中复制/粘贴的。现在,Quaternion.cpp 看起来像这样:

float& Quaternion::operator[](const int &idx)
{
    if(idx == 0)
    {
        return x;
    }
    if(idx == 1)
    {
        return y;
    }
    if(idx == 2)
    {
        return z;
    }
    if(idx == 3)
    {
        return w;
    }
    std::cerr << "Your Quaternion is only accessible at positions {0, 1, 2, 3}!" 
              << std::endl;
    return x;
}

const float& Quaternion::operator[](const int &idx)
{
    if(idx == 0)
    {
        return const x;
    }
    if(idx == 1)
    {
        return const y;
    }
    if(idx == 2)
    {
        return const z;
    }
    if(idx == 3)
    {
        return const w;
    }
    std::cerr << "Your Quaternion is only accessible at positions {0, 1, 2, 3}!" 
         << std::endl;
    return x;
}

我收到签名“const float& Quaternion::operator[](const int &idx)”的错误。

之前发生的另一件事是,如果超出边界,我无法返回 0。也许我会,一旦这个问题得到解决,但它之前给了我一条错误消息。我刚回来x,这让我很不高兴。

最佳答案

您从第二个 (const) 运算符实现中遗漏了尾随 const 修饰符:

const float& Quaternion::operator[](const int &idx) const
{
    // ...
}

关于c++ - "error: expected unqualified-id before ' float ' "用于 operator[] 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13555151/

相关文章:

c++ - 不同类如何操作一个函数一个

c++ - 为什么这个延迟循环在没有 sleep 的几次迭代后开始运行得更快?

acdbEntGet 和 acdbEntGetX 的 C# 包装器

c++ - 如何在复制构造函数中调用重载的下标?

c++ - 无法在 C++ 中重载输出流

c# - 在固定语句中使用三元条件运算符

c# - 在 C# 中,x+=y 和 x=x+y(x 和 y 都是简单类型)之间是否存在任何性能差异?

c - 按位逻辑运算符和移位运算符

c++派生结构来管理不同的版本

c++ - 在着色器程序中重新编译、重新链接、顶点着色器