c++ - 重载类函数运算符两次作为 setter 和 getter

标签 c++ function operator-keyword

我有一个类,我想重载函数调用运算符。但是由于 C++ 标准禁止声明两个仅返回类型不同的相似方法,因此我得到了编译错误 C2556。我想将函数用作 getter 和 setter 方法。我知道我可以通过创建一个 get 和一个 set 函数来实现这一点。所以问题是:有没有办法以某种方式实现这一目标?

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

最佳答案

解决这个问题的传统方法是使用const,比如:

#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;
}

现在,当您想要修改或不修改对象时,编译器将使用“适当”的方法。 (如果你在 const 设置中使用 Foo,你只需要 const 运算符)

关于c++ - 重载类函数运算符两次作为 setter 和 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27267328/

相关文章:

c++ - 如何安排一个操作在未来的时间运行

c++ - C++ 字符串类型数组

swift - 在枚举中生成随机类型的静态函数会导致崩溃并出现错误 "unexpectedly found nil when unwrapping an Optional value"

c# - 运算符 == 是如何选择的?

c++ - 重载 C++ == 运算符

c++ - 来自 std::any 的足够散列

javascript - 清除已完成任务按钮待办事项列表

c++ - 如何在设置字符串值时优化函数调用?

javascript - + javascript 中表达式前的运算符 : what does it do?

python - Socket编程--发送和接收图像