为什么不允许 "empty attribute block"?
Why is an "empty attribute block" not allowed?
这可能是今天提出的最愚蠢的问题,但无论如何我都会继续:
以下带有重载运算符 +=
的派生 class,重载运算符 []
的基础 class 给出以下编译器错误:
empty attribute block is not allowed
我通常会在运算符 +=
中写 v[0]
和 v[1]
当然,但是我很好奇它是否可以编译,如果不能,为什么不能。
什么是属性块?为什么编译器不将 [0]
解析为 []
运算符,从基 class 返回引用?仅仅是语法问题还是更深层次的问题?
#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;
}
这可能是今天提出的最愚蠢的问题,但无论如何我都会继续:
以下带有重载运算符 +=
的派生 class,重载运算符 []
的基础 class 给出以下编译器错误:
empty attribute block is not allowed
我通常会在运算符 +=
中写 v[0]
和 v[1]
当然,但是我很好奇它是否可以编译,如果不能,为什么不能。
什么是属性块?为什么编译器不将 [0]
解析为 []
运算符,从基 class 返回引用?仅仅是语法问题还是更深层次的问题?
#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;
}