运算符 [] 重载的"error: expected unqualified-id before 'float' "

"error: expected unqualified-id before 'float' " for operator[] overload

本文关键字:unqualified-id before float expected 重载 error 运算符      更新时间:2023-10-16

>我试图为我的一个容器实现运算符[]。但是我对c ++真的很陌生,似乎我的实现中有一个错误。

我是这样宣布的:

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

这应该没问题,它几乎是从教程中复制/粘贴的。现在,四元数.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
{
    // ...
}