C++ Protected / Public overloads

混江龙づ霸主 提交于 2019-12-01 19:47:40

It is not possible to overload on return value. Non-const method will be used when the object is non-const. It is possible to guide the compiler by:

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

Or possibly nicer solution is to have the constant method have different name (eg.: ConstV). Or you can just add this new method and leave the current method there. This approach is used in C++0x standard. For example constant methods cbegin() and cend() have been added to standard containers.

Overload resolution does not take member accessibility into account, so an ideal overload candidate is chosen and then member accessibility is checked to see if the call is legal.

The 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;

Since foo is not const compiler is trying to use the 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;

You are close to the solution. The compiler will select the const function if the 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; 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!