Overload class function operator twice as setter and getter

我的梦境 提交于 2020-01-04 03:57:07

问题


I have a class and i want to overload the fuction-call operator. But since the C++ standard forbids declaring two similar methods which only differ in return type, i get the compile error C2556. I want to use the functions as getter and setter methods. I know i can achieve this by creating a get and a set function. So the question is : Is there a way to achieve this somehow?

class Foo
{
    private:
        std::vector<int> m_vec;

    public:
        Foo()
        {
            m_vec.push_back(1);
            m_vec.push_back(2);
            m_vec.push_back(3);
        }

        //Getter
        int operator()(int i)
        {
            return m_vec.at(i);
        }

        //Setter (C2556)
        int& operator()(int i)
        {
            return m_vec.at(i);
        }
};

int main()
{
    Foo foo;
    foo(1) = 10; //use the setter 
    int i = foo(1); //use the getter
    return 0;
}

回答1:


The traditional way of solving this problem is to use const, such as:

#include <vector>

class Foo
{
    private:
        std::vector<int> m_vec;

    public:
        Foo()
        {
            m_vec.push_back(1);
            m_vec.push_back(2);
            m_vec.push_back(3);
        }

        //Setter
        int& operator()(int i)
        {
            return m_vec.at(i);
        }
        //getter
        int operator()(int i) const
        {
            return m_vec.at(i);
        }
};

int main()
{
    Foo foo;
    foo(1) = 10; //use the setter 
    int i = foo(1); //use the getter
    const Foo& b = foo;
    int j = b(1);
    return 0;
}

Now the compiler will use the "appropriate" method when you want to modify vs. not modify the object. (You only need the const operator if you ever use Foo in a const setting)




回答2:


To my understanding, the first overload is not necessary. It is sufficient to overload

int& operator()(int i)
{
    return m_vec.at(i);
}

which then serves as both getter and setter. The subject is also discussed here.



来源:https://stackoverflow.com/questions/27267328/overload-class-function-operator-twice-as-setter-and-getter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!