Skip to content

Commit 502ffe5

Browse files
ibellwjakob
authored andcommitted
Add docs and tests for unary op on class (#1814)
1 parent a1b71df commit 502ffe5

File tree

3 files changed

+12
-7
lines changed

3 files changed

+12
-7
lines changed

docs/advanced/classes.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -662,6 +662,7 @@ to Python.
662662
.def(py::self *= float())
663663
.def(float() * py::self)
664664
.def(py::self * float())
665+
.def(-py::self)
665666
.def("__repr__", &Vector2::toString);
666667
}
667668

tests/test_operator_overloading.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ class Vector2 {
2323

2424
std::string toString() const { return "[" + std::to_string(x) + ", " + std::to_string(y) + "]"; }
2525

26+
Vector2 operator-() const { return Vector2(-x, -y); }
2627
Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
2728
Vector2 operator-(const Vector2 &v) const { return Vector2(x - v.x, y - v.y); }
2829
Vector2 operator-(float value) const { return Vector2(x - value, y - value); }
@@ -104,6 +105,7 @@ TEST_SUBMODULE(operators, m) {
104105
.def(float() - py::self)
105106
.def(float() * py::self)
106107
.def(float() / py::self)
108+
.def(-py::self)
107109
.def("__str__", &Vector2::toString)
108110
.def(hash(py::self))
109111
;

tests/test_operator_overloading.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ def test_operator_overloading():
99
assert str(v1) == "[1.000000, 2.000000]"
1010
assert str(v2) == "[3.000000, -1.000000]"
1111

12+
assert str(-v2) == "[-3.000000, 1.000000]"
13+
1214
assert str(v1 + v2) == "[4.000000, 1.000000]"
1315
assert str(v1 - v2) == "[-2.000000, 3.000000]"
1416
assert str(v1 - 8) == "[-7.000000, -6.000000]"
@@ -44,13 +46,13 @@ def test_operator_overloading():
4446
del v2
4547
assert cstats.alive() == 0
4648
assert cstats.values() == ['[1.000000, 2.000000]', '[3.000000, -1.000000]',
47-
'[4.000000, 1.000000]', '[-2.000000, 3.000000]',
48-
'[-7.000000, -6.000000]', '[9.000000, 10.000000]',
49-
'[8.000000, 16.000000]', '[0.125000, 0.250000]',
50-
'[7.000000, 6.000000]', '[9.000000, 10.000000]',
51-
'[8.000000, 16.000000]', '[8.000000, 4.000000]',
52-
'[3.000000, -2.000000]', '[3.000000, -0.500000]',
53-
'[6.000000, -2.000000]']
49+
'[-3.000000, 1.000000]', '[4.000000, 1.000000]',
50+
'[-2.000000, 3.000000]', '[-7.000000, -6.000000]',
51+
'[9.000000, 10.000000]', '[8.000000, 16.000000]',
52+
'[0.125000, 0.250000]', '[7.000000, 6.000000]',
53+
'[9.000000, 10.000000]', '[8.000000, 16.000000]',
54+
'[8.000000, 4.000000]', '[3.000000, -2.000000]',
55+
'[3.000000, -0.500000]', '[6.000000, -2.000000]']
5456
assert cstats.default_constructions == 0
5557
assert cstats.copy_constructions == 0
5658
assert cstats.move_constructions >= 10

0 commit comments

Comments
 (0)