C ++ protected / public overload

I have a class like this:

class Foo { public: Foo() { for(int i = 0; i < 10; ++i) v.push_back(i); }; const vector<double>& V() const {return v;}; protected: vector<double>& V() {return v;}; private: vector<double> v; }; 

And then the code snippet is as follows:

 Foo foo; for(int i = 0; i < (int) foo.V().size(); ++i) cout << foo.V().at(i) << endl; () size (); ++ i) Foo foo; for(int i = 0; i < (int) foo.V().size(); ++i) cout << foo.V().at(i) << endl; 

However, the latter is a compilation error, saying that the call to V() is a secure method as long as I'm just trying to read it, not change it.

I tried the following (but unsuccessfully).

 Foo foo; const vector<double>& test = foo.V(); for(int i = 0; i < (int) test.size(); ++i) cout << test.at(i) << endl; foo.V (); Foo foo; const vector<double>& test = foo.V(); for(int i = 0; i < (int) test.size(); ++i) cout << test.at(i) << endl; ); ++ i) Foo foo; const vector<double>& test = foo.V(); for(int i = 0; i < (int) test.size(); ++i) cout << test.at(i) << endl; 

Many thanks for your help.

=====

Thank you all for explanations and solutions! He is very grateful!

+4
source share
4 answers

It is impossible to overload the return value. Non-const method will be used when the object is not const. The compiler guide can include:

 const vector<double>& test = const_cast<Foo const&>(foo).V(); 

Or, perhaps, the best solution is to have a permanent method with a different name (for example: ConstV ). Or you can simply add this new method and leave there the current method. This approach is used in the C ++ 0x standard. For example, in standard methods containers constants were added cbegin() and cend() .

+5
source

Overload Resolution does not consider the items are available, so choose the perfect candidate for overload, and then access the element is checked to see if the call is legitimate.

Realistic workaround is:

 Foo foo; Foo const& foo_alias = foo; for (std::size_t i = 0; i != foo_alias.V().size(); ++i) cout << foo_alias.V().at(i) << endl; size (); ++ i) Foo foo; Foo const& foo_alias = foo; for (std::size_t i = 0; i != foo_alias.V().size(); ++i) cout << foo_alias.V().at(i) << endl; 
+5
source

Since foo is not const , the compiler attempts to use a non-const method. As a workaround, you can do the following:

  Foo foo; const Foo& cFoo = foo; for(int i = 0; i < (int) cFoo.V().size(); ++i) cout << cFoo.V().at(i) << endl; 
+2
source

You are close to a solution. The compiler chooses the function const , if Foo is also const .

 Foo foo; const Foo& cfoo = foo; for(int i = 0; i < (int) cfoo.V().size(); ++i) cout << cfoo.V().at(i) << endl; () size (); ++ i) Foo foo; const Foo& cfoo = foo; for(int i = 0; i < (int) cfoo.V().size(); ++i) cout << cfoo.V().at(i) << endl; 
+1
source

All Articles