在C++中创建自己的运算符**?
Create own operator ** in C++?
有一个扩展std::array的泛型类Vector,以及一个定义向量可能表达式的泛型类Expression。
例如:
向量 A({1,2,3});
向量 B({2,2,2});
和表达式:
A + B;
A * B;
A - B;
A/B;
现在我需要这个表达式 A ** B,它返回一个双精度作为两个向量 A 和 B 的标量产生,结果必须是:2+4+6=12。问题是运算符的实现**!!
我该如何编写此运算符**?
我的想法是重载返回指针的 Vector 的取消引用运算符*,然后重载结构 Mul oder 乘法运算符* ...无法解决此错误:
"不存在从"表达式<...>"到"double"的合适转换函数">
template<typename Left, typename Op, typename Right> class Expression {
const Left& m_left;
const Right& m_right;
public:
typedef typename Left::value_type value_type;
// Standard constructor
Expression(const Left& l, const Right& r) : m_left{ l }, m_right{ r } {}
size_t size() const {
return m_left.size();
}
value_type operator[](int i) const {
return Op::apply(m_left[i], m_right[i]);
}
};
struct Mul {
template<typename T> static T apply(T l, T r) {
return l * r;
}
};
template<typename Left, typename Right>
Expression<Left, Mul, Right> operator*(const Left& l, const Right& r) {
return Expression<Left, Mul, Right>(l, r);
}
.......................
// Class Vector extends std::array
template<class T, size_t S> class Vector : public array<T, S> {
public:
// Standard constructor
Vector<T, S>(array<T, S>&& a) : array<T, S>(a) {}
// Initializerlist constructor
Vector(const initializer_list<T>& data) {
size_t s = __min(data.size(), S);
auto it = data.begin();
for (size_t i = 0; i < s; i++)
this->at(i) = *it++;
}
};
.....................................
int main {
Vector<double, 5> A({ 2, 3, 4, 5, 6 });
Vector<double, 5> B({ 3, 3, 3, 3, 3 });
Vector<double, 5> C;
C = A * B; // is a Vector: [6, 9, 12, 15, 18] and it works.
double d = A**B; // but this one does not work, the error message is: "no suitable conversion function from "Expression<Vector<double, 5U>, Mul, Vector<double, 5U> *>" to "double" exists"
cout << d << endl; // must give me: 60
}
你可以这样做
#include <iostream>
using namespace std;
struct V
{
struct Vhelper
{
Vhelper(const V& v) : v(v) {}
const V& v;
};
V operator*(const V&) const {
cout << "* calledn";
return V();
}
double operator*(const Vhelper&) const {
cout << "** calledn";
return 42;
}
Vhelper operator*() { return Vhelper(*this); }
};
int main() {
V a, b, c;
a = b * c;
double d = b ** c;
return 0;
}
但是你应该忘记,在你的作品被评分之后,这是可能的。切勿在实际代码中执行此操作。
这不是一个成熟的operator**
因为它不能在可以使用真实**
运算符的所有上下文中使用(如果要将其用于电源操作,它具有错误的优先级和关联性)。但是对于一个有趣的学习项目来说,这应该是可以的。
相关文章:
- 重载 + 自己的类和 std::string 的运算符
- 在C++中,我可以在定义自己的复制构造函数后跳过定义赋值运算符吗?
- 在编写自己的流运算符时,如何检查当前的 ostream dec/hex 模式?
- 如何在我自己的类中重载"+"和"<<"运算符
- 什么是编程语言支持定义您自己的自定义运算符?
- C++模运算符,使用 #define 和自己的类进行浮点运算
- 如何在我自己的类 Vector 中使用 Move 构造函数而不是 Move 赋值运算符
- C 超载相等运算符.我应该写自己的功能以接受通过参考或值传递的参数
- 在C++中创建自己的运算符**?
- 运算符重载 (+=,=) 用于自己的字符串
- 不能为我自己的类重载运算符<<
- 自己的矩阵类乘法运算符
- std::istream&运算符>>和自己的向量类
- 在函数中使用时自己的运算符+的奇怪行为(Point3D(0,0,0)+点)
- 在某些情况下,编写自己的复制构造函数而不是自己的赋值运算符是个好主意吗
- 使用自己的比较器运算符()进行映射<>。在找不到 KEY 的情况下给出错误
- 我自己的运算符'+','-'
- 在我自己的算术中重载运算符+
- 创建了我自己的向量类.可以重载流运算符,但不能按值c++打印
- boost.log std::异常格式化程序找不到运算符<< 自己的命名空间中的重载