home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!haven.umd.edu!darwin.sura.net!news.cua.edu!cuavax.dnet.cua.edu!48ganelin
- From: 48ganelin@cuavax.dnet.cua.edu
- Subject: HELP: mixing const and non const function
- Message-ID: <1992Jul21.182115.1@cuavax.dnet.cua.edu>
- Lines: 49
- Sender: news@netcon.cua.edu (USENET News System)
- Organization: The Catholic University of America
- Date: Tue, 21 Jul 1992 22:21:15 GMT
-
- How to solve the next problem:
- I want to declare a function to be constant though it
- uses a nonconstant function.
- (Of course it is an error for usual situation, but see example)
-
- Example:
-
- class foo {
- int vector [10] ;
- public:
- int& operator () (int at) { return vector[at] ; }
- };
-
- class foo2
- {
- foo f ;
- int median (void) const { return f(5); } <----- warning
- };
-
-
- I got the warning
-
- 10: Non-const function foo::operator ()(int)
- called for const object in function foo2::median() const
-
- (as it should be, of course).
-
- I do not want to declare operator () to be constant, because I
- want to use it as both rvalue and lvalue. How can I sovle this
- problem: avoid this warning?
-
- Possible solution, which I do not like.
-
- 1. To introduce second method
-
- int elem (int at) const {return vector[at] ;}
-
- to access element only as rvalue and then
-
- function median (void) const { return f.elem(5) ;}
-
- What I want is to "explain" the translator, that operator () in
- the right part is --const-- and in the left it is --non const--.
- Is it possilbe to do? Any trick?
- ( Other words, f(5) and vector[5] should be absolutely the same from the
- translator's point of view)
-
- Thanks,
- Pavel Ganelin.
-