Mercurial > ~dholland > hg > ag > index.cgi
view tests/agcl/ffcalc/number.h @ 6:607e3be6bad8
Adjust to the moving target called the C++ standard.
Apparently nowadays it's not allowed to define an explicit copy
constructor but not an assignment operator. Consequently, defining the
explicit copy constructor in terms of the implicit/automatic
assignment operator for general convenience no longer works.
Add assignment operators.
Caution: not tested with the IBM compiler, but there's no particular
reason it shouldn't work.
author | David A. Holland |
---|---|
date | Mon, 30 May 2022 23:46:22 -0400 |
parents | 13d2b8934445 |
children |
line wrap: on
line source
#ifndef NUMBER_H #define NUMBER_H #include <stdio.h> #include <assert.h> class Number { double value; int valid; int *useCount; int serialNumber; static int nCreated; static char buf[]; void logCreation() {*useCount = 1; printf("Create: %d\n", serialNumber); fflush(stdout); } public: Number() : valid(0), useCount(new int), serialNumber(nCreated++) {logCreation();} Number(double d) : value(d), valid(1), useCount(new int), serialNumber(nCreated++) {logCreation();} Number(const Number &n) : value(n.value), valid(n.valid), useCount(n.useCount), serialNumber(n.serialNumber) { (*useCount)++; printf("Copy constructor: %s\n", n.asString()); printf("Copy constructor: %s\n", asString()); fflush(stdout); } ~Number() { assert(*useCount > 0); if (--(*useCount) == 0) printf("Delete %d\n", serialNumber); else printf("Destructor: %s\n", asString()); fflush(stdout); } char *asString() const { char *vs = valid ? "valid" : "invalid"; sprintf(buf, "%X: sn%d(%s) = %G, *%X = %d", this, serialNumber, vs, value, useCount, *useCount); return buf; } Number &operator = (const Number &n) { assert(*useCount > 0); if (--(*useCount) == 0) printf("Delete %d\n", serialNumber); fflush(stdout); useCount = n.useCount; value = n.value; valid = n.valid; serialNumber = n.serialNumber; (*useCount)++; return *this; } Number &operator += (const Number &n) {valid |= n.valid; value += n.value; return *this;} Number &operator -= (const Number &n) {valid |= n.valid; value -= n.value; return *this;} Number &operator *= (const Number &n) {valid |= n.valid; value *= n.value; return *this;} Number &operator /= (const Number &n) {valid |= n.valid; if(valid) value /= n.value; return *this;} Number &operator -() {value = -value; return *this;} operator char * () { if (valid) { sprintf(buf, "%G", value); printf("operator char * = %g\n", value); return buf; } else return "Invalid"; } }; #endif