home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 33,323 of 33,346   
   James K. Lowden to MARH   
   Re: Class to behave like ints   
   09 May 14 06:11:39   
   
   From: jklowden@speakeasy.net   
      
   On Thu,  8 May 2014 06:47:53 CST   
   MARH  wrote:   
      
   > Perhaps I haven't made myself clear, I have a whole set of apples,   
   > with ids; for example:   
   >   
   > AppleID a(7), b(99), c(33);   
   >   
   > And likewise pears with their own ids:   
   >   
   > PearID p(7), q(8), r(1000000)   
   >   
   > and I don't want to be able to compile:   
   >   
   > a = p;   // Bad!   
   > a = b;   // Good.   
      
   If the values (7, 99, 33, etc.) are known at compile time, then enum is   
   your friend.  You haven't said so, but I take it the values are not   
   known, that some external source presents you with integers   
   representing apples and pears, and you'd like to classify them and use   
   C++ to keep them distinct.   
      
   In that case a simple class suffices.  The simplest class (I say   
   boldly) is a struct:   
      
   struct AppleID { int id; AppleID( int id=0 ) : id(id) {} };   
   struct PearID { int id; PearID( int id=0 ) : id(id) {} };   
      
   thus   
      
   > AppleID a(7), b(99), c(33);   
   > PearID p(7), q(8), r(1000000)   
   > a = p;   // Bad!   
   > a = b;   // Good.   
      
   all work, assuming you want a.id == 99 post-assignment.   
      
   In both cases (enum and struct) you're creating a user-defined type,   
   and determining its arithmetic and interchangeablilty properties.   
      
   HTH.   
      
   --jkl   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca