这可能是今天提出的最愚蠢的问题,但无论如何我都要按下:
以下带有重载运算符+=
的派生类,其基类重载运算符[]
会产生以下编译器错误:
不允许使用空属性块
我当然会在运算符v[0]
中写v[1]
和+=
,但我很好奇它是否会编译,如果没有,为什么不呢。
什么是属性块?为什么编译器不会将[0]
解析为[]
运算符,从基类返回引用?只是语法问题或更深层次的问题?
#include <array>
template<class T, int C>
struct Vec
{
typedef T value_type;
typedef unsigned index_type;
typedef unsigned size_type;
std::array<T, C> v;
template<typename ...Args>
explicit Vec(Args&&... args) : v({{args...}}) {}
Vec(std::array<T, C> const & o) : v(o) {}
value_type & operator [] (index_type i)
{
return v[i];
}
value_type const & operator [] (index_type i) const
{
return v[i];
}
};
template<class T>
struct Vec2 : Vec<T, 2>
{
template<typename ...Args>
explicit Vec2(Args... args) : Vec<T, 2>(args...) {}
Vec2(Vec2<T> const & p) : Vec<T, 2>(p.v) {}
Vec2<T> & operator += (Vec2<T> const & q)
{
[0] += q[0];
[1] += q[1];
return *this;
}
};
int main(void)
{
Vec2<int> a(10, 20);
Vec2<int> b(30, 40);
a += b;
return 0;
}
答案 0 :(得分:5)
你不能以这种方式使用运营商自由形式。您必须明确提供this
,例如(*this)[0]
。引用属性的错误消息只是因为[]
也可用于表示属性。
答案 1 :(得分:3)
将operator+=
更改为调用operator[]
,[0]
之类的语句不是有效的C ++。
Vec2<T> & operator += (Vec2<T> const & q)
{
operator[](0) += q[0];
operator[](1) += q[1];
return *this;
}