Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!sun-barr!apple!bbn.com!saustin From: saustin@bbn.com (Steve Austin) Newsgroups: comp.lang.c++ Subject: Re: Transparent int class (we second the problem) Message-ID: <60198@bbn.BBN.COM> Date: 19 Oct 90 05:08:46 GMT References: Sender: news@bbn.com Distribution: comp Lines: 66 zmls04@trc.amoco.com (Martin L. Smith) writes: >In article matthew@hydra.ua.oz.au (Matthew Donaldson) writes: > The aim is to be able to do something like this: > ProtectedInt a; > ... > a= 2; > cout << "Now a is " << a << "\n"; > and everything else you can do with ints, such as > a |= 2, fn(a), int b= a, ProtectedInt b=a, etc. > [ as an aside, how are operations like |= handled? There is no operator|= ] > Also, is there a more general solution to the whole problem, rather than > having to define every operator for the class to perform operations on ints. >We've run into the same problem and, to us, it is the most serious >(apparent) structural limitation in providing well-packaged user-defined >data types in C++. Is there a clean, general solution? I may be missing something here, but by providing cast operators to and from the new form of int's (called here pint's) you can get the usual integer operators do most of the work and just define the operations that you want to define. The program below shows how simple the definition can be - I could add specific operators, such as "pint operator *(pint, pint)" to redefine a multiplication which (eg) check for possible overflow. Hope this helps Steve Austin ------------------------------------------------------------------------------- loki:tmp> cat pint.cc #include class pint { int value; public: pint(int i = 0) { value = i; }; operator int() { return value; }; }; main() { pint a = 4; pint b(3); pint c = a+b; pint d(c+2); printf("%d %d\n", int(c), int(d-2)); c = 2; c |= a; // there *is* an opeator |= printf("%d\n", int(c)); exit(0); } loki:tmp> g++ -o pint pint.cc loki:tmp> ./pint 7 7 6 loki:tmp> exit