为什么不允许"empty attribute block"?



这可能是今天问的最愚蠢的问题,但无论如何我还是要继续:

具有重载操作符+=的派生类,其基类重载操作符[],会产生以下编译错误:

空属性块不允许

我通常会在操作符+=中写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;
}

不能这样使用自由形式的操作符。必须显式地提供this,例如(*this)[0]。引用属性的错误消息很简单,因为[]也可以用来表示属性。

operator+=改为调用operator[],像[0]这样的语句不是有效的c++。

    Vec2<T> & operator += (Vec2<T> const & q)
{
    operator[](0) += q[0];
    operator[](1) += q[1];
    return *this;
}

最新更新