Посыпаю голову пеплом, не знаток C++, исправил:
#include <iostream>
#include <limits>
using namespace std;
struct resistor {
double val;
resistor(double ival) : val(ival) {}
resistor(void) {val=numeric_limits<double>::signaling_NaN();}
resistor operator||(const resistor b) {
return resistor(1/(1/val+1/b.val));
}
resistor operator-(const resistor b) {
return resistor(val+b.val);
}
resistor operator=(double nval) {
val=nval;
return resistor(nval);
}
};
ostream& operator<<(ostream &s, const resistor r) {
if (r.val!=r.val || r.val<0) throw r.val;
if (r.val<1e3) s<<r.val<<"ohm";
else if (r.val<1e6) s<<r.val/1e3<<"k";
else if (r.val<1e9) s<<r.val/1e6<<"M";
else s<<r.val/1e9<<"G";
return s;
}
int main()
{
resistor R1(2e3), R2;
R2=3e3;
resistor R3=R1||R2;
cout << "R1||R2=" << R3 << "\n";
cout << "R1-R2=" << (R1-R2) << "\n";
return 0;
}
Было:
$ valgrind --leak-check=full ./a.out
==9709== HEAP SUMMARY:
==9709== in use at exit: 16 bytes in 2 blocks
==9709== total heap usage: 2 allocs, 0 frees, 16 bytes allocated
==9709==
==9709== 8 bytes in 1 blocks are definitely lost in loss record 1 of 2
==9709== at 0x4025B64: operator new(unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==9709== by 0x80489B8: resistor::operator||(resistor const&) (test.cpp:15)
==9709== by 0x8048886: main (test.cpp:39)
==9709==
==9709== 8 bytes in 1 blocks are definitely lost in loss record 2 of 2
==9709== at 0x4025B64: operator new(unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==9709== by 0x80489FA: resistor::operator-(resistor const&) (test.cpp:18)
==9709== by 0x80488D4: main (test.cpp:41)
==9709==
==9709== LEAK SUMMARY:
==9709== definitely lost: 16 bytes in 2 blocks
==9709== indirectly lost: 0 bytes in 0 blocks
==9709== possibly lost: 0 bytes in 0 blocks
==9709== still reachable: 0 bytes in 0 blocks
==9709== suppressed: 0 bytes in 0 blocks
==9709==
==9709== For counts of detected and suppressed errors, rerun with: -v
==9709== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 17 from 6)