diff --git a/docs/advanced/classes.rst b/docs/advanced/classes.rst index c9a0da5a1..ae5907dee 100644 --- a/docs/advanced/classes.rst +++ b/docs/advanced/classes.rst @@ -662,6 +662,7 @@ to Python. .def(py::self *= float()) .def(float() * py::self) .def(py::self * float()) + .def(-py::self) .def("__repr__", &Vector2::toString); } diff --git a/tests/test_operator_overloading.cpp b/tests/test_operator_overloading.cpp index 8ca7d8bcf..7b111704b 100644 --- a/tests/test_operator_overloading.cpp +++ b/tests/test_operator_overloading.cpp @@ -23,6 +23,7 @@ public: std::string toString() const { return "[" + std::to_string(x) + ", " + std::to_string(y) + "]"; } + Vector2 operator-() const { return Vector2(-x, -y); } Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); } Vector2 operator-(const Vector2 &v) const { return Vector2(x - v.x, y - v.y); } Vector2 operator-(float value) const { return Vector2(x - value, y - value); } @@ -104,6 +105,7 @@ TEST_SUBMODULE(operators, m) { .def(float() - py::self) .def(float() * py::self) .def(float() / py::self) + .def(-py::self) .def("__str__", &Vector2::toString) .def(hash(py::self)) ; diff --git a/tests/test_operator_overloading.py b/tests/test_operator_overloading.py index 86827d2ba..bd36ac2a5 100644 --- a/tests/test_operator_overloading.py +++ b/tests/test_operator_overloading.py @@ -9,6 +9,8 @@ def test_operator_overloading(): assert str(v1) == "[1.000000, 2.000000]" assert str(v2) == "[3.000000, -1.000000]" + assert str(-v2) == "[-3.000000, 1.000000]" + assert str(v1 + v2) == "[4.000000, 1.000000]" assert str(v1 - v2) == "[-2.000000, 3.000000]" assert str(v1 - 8) == "[-7.000000, -6.000000]" @@ -44,13 +46,13 @@ def test_operator_overloading(): del v2 assert cstats.alive() == 0 assert cstats.values() == ['[1.000000, 2.000000]', '[3.000000, -1.000000]', - '[4.000000, 1.000000]', '[-2.000000, 3.000000]', - '[-7.000000, -6.000000]', '[9.000000, 10.000000]', - '[8.000000, 16.000000]', '[0.125000, 0.250000]', - '[7.000000, 6.000000]', '[9.000000, 10.000000]', - '[8.000000, 16.000000]', '[8.000000, 4.000000]', - '[3.000000, -2.000000]', '[3.000000, -0.500000]', - '[6.000000, -2.000000]'] + '[-3.000000, 1.000000]', '[4.000000, 1.000000]', + '[-2.000000, 3.000000]', '[-7.000000, -6.000000]', + '[9.000000, 10.000000]', '[8.000000, 16.000000]', + '[0.125000, 0.250000]', '[7.000000, 6.000000]', + '[9.000000, 10.000000]', '[8.000000, 16.000000]', + '[8.000000, 4.000000]', '[3.000000, -2.000000]', + '[3.000000, -0.500000]', '[6.000000, -2.000000]'] assert cstats.default_constructions == 0 assert cstats.copy_constructions == 0 assert cstats.move_constructions >= 10