home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / cplus / 11280 < prev    next >
Encoding:
Text File  |  1992-07-21  |  1.6 KB  |  60 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!haven.umd.edu!darwin.sura.net!news.cua.edu!cuavax.dnet.cua.edu!48ganelin
  3. From: 48ganelin@cuavax.dnet.cua.edu
  4. Subject: HELP: mixing const and non const function
  5. Message-ID: <1992Jul21.182115.1@cuavax.dnet.cua.edu>
  6. Lines: 49
  7. Sender: news@netcon.cua.edu (USENET News System)
  8. Organization: The Catholic University of America
  9. Date: Tue, 21 Jul 1992 22:21:15 GMT
  10.  
  11. How to solve the next problem:
  12.  I want to declare a function to be constant though it
  13.  uses a nonconstant function.
  14.  (Of course it is an error for usual situation, but see example)
  15.  
  16.  Example:
  17.  
  18. class foo {
  19.     int vector [10] ;
  20. public:
  21.     int& operator () (int at)  { return vector[at] ; }
  22. };
  23.  
  24. class foo2
  25. {
  26.    foo f ;
  27.    int median (void) const { return f(5); }           <----- warning
  28. };
  29.  
  30.  
  31. I got the warning
  32.  
  33. 10: Non-const function foo::operator ()(int)
  34.     called for const object in function foo2::median() const
  35.  
  36. (as it should be, of course).
  37.  
  38. I do not want to declare operator () to be constant, because I
  39. want to use it as both rvalue and lvalue. How can I sovle this
  40. problem:  avoid this warning?
  41.  
  42. Possible solution, which I do not like.
  43.  
  44. 1. To introduce second method
  45.  
  46.     int elem (int at) const {return vector[at] ;}
  47.  
  48. to access element only as rvalue and then
  49.  
  50.     function median (void) const { return f.elem(5) ;}
  51.  
  52. What I want is to "explain" the translator, that operator () in
  53. the right part is --const-- and in the left it is --non const--.
  54. Is it possilbe to do? Any trick?
  55. ( Other words, f(5) and vector[5] should be absolutely the same from the
  56. translator's point of view)
  57.  
  58. Thanks,
  59. Pavel Ganelin.
  60.