它可以通过引用传递从类到全局函数或类之间的方法吗?

时间:2016-12-01 19:23:40

标签: c++ c++14 pass-by-reference

我想知道它是否可以通过引用从类到全局函数的方法来传递?

考虑这个,例如:

void FuncSet(int* x)
{
    *x = 4;
}

void (&RefSet)(int*) = FuncSet; // reference to FuncSet();

现在,我尝试过类似的事情:

class x
{
    public:
        int SetSome(int* x)
        {
             *x = 4;
        }
};
int(&DeclRef)(int*) = x::SetSome;

我获得了类似的东西:

 [Error] invalid initialization of non-const reference of type 'int
 (&)(int*)' from an rvalue of type 'int (x::*)(int*)'

或按类分类:

class x
{
    public:
        int SetSome(int * x)
        {
            *x = 4; 
        }
};


class y
{
    public:
        int (&RefSet)(int*); // i can't do something like this: int(y::&RefSet)(int*);
};
int(y::RefSet)(int*) = x::SetSome; // same.

这有可能吗?

1 个答案:

答案 0 :(得分:1)

您可以拥有成员指针:

int (X::*DeclRef)(int*) = &x::SetSome;

使用

X x;
int i;
(x.*DeclRef)(&i);