我试图为我的一个容器实现 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/