C++ Protected / Public overloads

后端 未结 4 1893
無奈伤痛
無奈伤痛 2021-01-19 05:28

I have a class like this :

class Foo
{
public:
    Foo()
    {
        for(int i = 0; i < 10; ++i)
            v.push_back(i);
    };
    const vector<         


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-19 06:10

    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& test = const_cast(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.

提交回复
热议问题