用方法代替成员赋值

Replace member assignement with methods

本文关键字:成员 赋值 方法      更新时间:2023-10-16

在c++中编写了一些代码之后,可能需要将对结构体或类的成员的访问更改为产生一些副作用的内容。在这种意义上,需要将成员的赋值重载为不同的对象。

Struct A{
int v;
}
int main(){
A a;
a.v=17;
}

有可能做这件事吗?如果不存在这种可能性,那么如何编写代码以允许灵活地将成员更改为其他成员呢?

对成员的每次访问都分为getter和setter似乎很麻烦,而且对于任何合理的使用都是不切实际的。

是的,使用代理:

struct A
{
    v_proxy v; 
private:
    struct v_proxy
    {
        v_proxy( int vv = 0 ) : v{ vv }
        {}
        //Write access
        v_proxy& operator=( int i )
        {
            //Put your new code here 
            return v = i;
        }
        //Read access
        operator int() const
        {
            return v;
        }
        int v;
    };
};
int main()
{
    A a;
    a.v = 0;
};

像这样编写一个通用的代理来允许在通用的非get/set语法中自定义读/写是很容易的。

EDIT:有人声称这不能正确地模仿c#属性的行为,因为在c#中我们可以从属性中访问this。只需要添加一个对象的引用并将其传递给代理函数。不要忘记将代理类设置为类的朋友,为this引用提供完全访问权限:

class A
{
    A() : v{ *this }
    {}
    friend struct v_proxy
    {
        v_proxy( A& ref , int vv = 0 ) : v{ vv } , This{ std::ref( ref )
        {}
        //Write access
        int& operator=( int i )
        {
            //Put your new code here, for example:
            This.foo();
            return v = i;
        }
        //Read access
        operator int() const
        {
            return v;
        }
        int v;
    private:
        std::reference_wrapper<A> This;
    };