重载类函数运算符,两次是setter和getter [英] Overload class function operator twice as setter and getter

查看:77
本文介绍了重载类函数运算符,两次是setter和getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

解决此问题的传统方法是使用const,例如:

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

现在,当您要修改对象而不要修改对象时,编译器将使用适当的"方法. (如果您在const设置中使用Foo,则仅需要const运算符)

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)

这篇关于重载类函数运算符,两次是setter和getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆