在下面一长串代码中,请寻找三个地方:
// "this->" can be omitted before first data[0]
和
// Compile error, if "this->" is omitted before first data[0]
和
// likewise, "this->" is required.
我不知道为什么有时“this->”可以省略,有时不能。
编译错误是:main.cpp:19:3: error: 'data' was not declared in this scope
它只是一个编译器错误吗?我的编译器是 GCC v4.8.1 和 v4.8.2。谢谢。顺便说一句,QtCreator 的默认智能感知,事实上,在所有三个地方都可以识别没有“this->”的 'data[0]'。
这是代码列表:
template <typename T>
struct Vec3_
{
T data[3];
inline Vec3_<T> & operator =(const Vec3_<T> & rhs) {
if (this != &rhs) {
data[0] = rhs.data[0]; // "this->" can be omitted before first data[0]
data[1] = rhs.data[1];
data[2] = rhs.data[2];
}
return *this;
}
};
template <typename T>
struct Vec3i_: Vec3_<T>
{
inline Vec3i_<T> & operator ^=(const Vec3i_<T> & rhs) {
data[0] ^= rhs.data[0]; // Compile error, if "this->" is omitted before first data[0]
this->data[1] ^= rhs.data[1];
this->data[2] ^= rhs.data[2];
return *this;
}
inline Vec3i_<T> operator ^(const Vec3i_<T> & rhs) const {
Vec3i_<T> tmp;
tmp[0] = this->data[0] ^ rhs.data[0]; // likewise, "this->" is required.
tmp[1] = this->data[1] ^ rhs.data[1];
tmp[2] = this->data[2] ^ rhs.data[2];
return tmp;
}
};
Vec3i_<int> A;
int main(int, char**) { return 0; }
== 更新 ==
由于有人指出了一个非常相似的问题(可能是重复的)和答案,并且该问题的标题甚至是描述性的,我将我的标题更改为与那个相似的标题(除了参数依赖差异)
然而,在阅读了该问题的答案后,我仍然感到困惑。答案指向一个常见问题[link here]说如果变量是非依赖名称,编译器将不会在基本模板类中搜索名称。然而,在这个例子中,变量 ( data
) 是一个从属名称,因为它的类型是T
,并且T
是模板变量。
我仍然愿意接受答案。