-1

In C++, how do i call a method member of class A from a class B, using a pointer? By the way Class A and B are of different types.

I read that when a pointer is pointing to member function it can only point member functions within the class. But how can i point to a member function outside the class?

for example:

class A
{
public:
    int add(int x)
    {
        return x+x;
    }
};

int main()
{
    typedef int (A::*pointer)();
    pointer func = &A::add;
    A objt;
    B objt2;

    obt2.*func(2);// the compiler give me an error of incompatible with object type ‘B’

    return 0;
}
4

2 回答 2

0

我认为您可以按如下方式运行它:

(*func)(&objt, 2)

更好的选择是使用 boost::bind/boost::function 代替:

boost::function<int(int)> func = boost::bind(&A::add, &objt, _1);
func(2);

我刚刚注意到您试图让它像 B 类的方法一样运行。这完全是荒谬的,但是如果您不关心正确性并且喜欢以完全不可预测的结果危险地生活,那么这样做会更容易:

((A *) &objt2)->add(2);
于 2012-04-13T21:49:13.633 回答
0

如果B使用A(调用 some的A成员)然后B 取决于A并且您可以通过简单地提供B指向A它可以调用A的方法的指针来实现这一点 - 请参见B1代码中的下面的类。

您可以将 's 成员的调用包装A到一个单独的对象 - 函子中。您可以通过将其实现为模板类并提供对象A地址、方法地址和参数来创建通用解决方案。为此,请参阅 class 的实现B2

class A
{
public:
    int add(int x)
    {
        return x+x;
    }
};

typedef int (A::*MEMFN)(int);

class B1
{
public:
    void InvokeAAdd(A* pA, int x)
    {
        cout << "result = " << pA->add(x) << endl;
    }
};

template<class T, typename TMemFn, typename TArg, typename TRetVal>
class B2
{
    T* pT;
    TMemFn memFn;
    TArg arg;
public:
    B2(T* pT, TMemFn memFn, TArg arg) : 
      pT(pT), memFn(memFn), arg(arg){}

    TRetVal operator()()
    {
        return (pT->*memFn)(arg);
    }
};

int main()
{
    A a;
    B1 b;
    b.InvokeAAdd(&a, 2);

    B2<A, MEMFN, int, int> b2(&a, &A::add, 2);
    cout << "result (via functor) = " << b2() << endl;
    return 0;
}

输出:

result = 4
result (via functor) = 4
于 2012-04-13T22:15:32.163 回答