重载模板运算符
Overloading template operators
我正试图在我的模板Vector类上重载+=运算器。
template<unsigned int dimensions, typename TValue>
class Vector
{
private:
std::array<TValue, dimensions> m_values;
public:
Vector(){
for (int i = 0; i < dimensions; i++){
m_values[i] = TValue();
}
};
Vector(std::array<TValue, dimensions> elements){
for (int i = 0; i < dimensions; i++){
m_values[i] = elements[i];
}
};
inline void set(VectorDimensions dimension, TValue value){
m_values[dimension] = value;
};
inline TValue get(VectorDimensions dimension) const{
return m_values[dimension];
};
inline unsigned int getSize() const{
return dimensions;
};
const std::array<TValue, dimensions> getValues() const{
return m_values;
};
friend ostream& operator<<(ostream& os, const Vector<dimensions, TValue>& vt) {
array<TValue, dimensions> values = vt.getValues();
os << '[';
for (unsigned int i = 0; i < vt.getSize(); i++){
os << values[i] << values[i+1] ? ", " : "";
}
os << ']';
return os;
};
friend Vector<dimensions, TValue>& operator+=(const Vector<dimensions, TValue>& vt) {
array<TValue, dimensions> values = vt.getValues();
for (unsigned int i = 0; i < vt.getSize(); i++){
m_values[i] += values[i];
}
return *this;
};
};
在为+=运算器添加过载后,我得到了以下许多错误:
错误C2805:二进制"operator+="的参数太少
错误C4430:缺少类型说明符-假定为int。注意:C++不支持默认的int
错误C2334:"{"之前的意外令牌;正在跳过明显的函数体。
错误C2238:";"前面有意外的令牌
语法错误:缺少";"在'<'之前
错误C2143:语法错误:缺少";"在"++"之前
错误C2143:语法错误:在";"之前缺少")"
错误C2059:语法错误:"return"
错误C2059:语法错误:"for"
错误C2059:语法错误:")"
解释一下为什么或如何导致这些错误,无论我做错了什么,都可能是有用的。感谢
我能够通过删除+=运算符定义之前的friend关键字来停止错误。根据本页http://en.cppreference.com/w/cpp/language/operators
class X {
public:
X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
{ // but often is, to modify the private members)
/* addition of rhs to *this takes place here */
return *this; // return the result by reference
}
// friends defined inside class body are inline and are hidden from non-ADL lookup
friend X operator+(X lhs, // passing first arg by value helps optimize chained a+b+c
const X& rhs) // alternatively, both parameters may be const references.
{
return lhs += rhs; // reuse compound assignment and return the result by value
}
};
这就是+和+=运算器过载的方式。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板