指向另一个对象的成员函数的指针

时间:2016-09-15 23:49:45

标签: c++ member-function-pointers

我的情况是这样的: 我有两个班:A,B。 A包含std::vector<B>,B需要来自A的函数指针来初始化它自己的操作。

(我试图在c ++中实现整数组和整数环数学结构)

最安全的方法是什么? (我了解到给B指向A的指针会导致A中的意外行为。我试了here。)

现在我在我的电脑上,我将发布我的代码库(我将B成员类设为A,以便最小化我必须输入的部分):

A.H

#ifndef A_H
#define A_H

#include <vector>

class A
{
    public:
        A(int);
        static int defaultMultiply(int, int);
        int multiply(int, int);
        class B
        {
            public: 
                typedef int(*defaultMultiplication)(int, int);
                typedef int(A::*multiplication)(int, int);
                B();
                B(int, int, multiplication);
                B operator*(const B&);

            protected:
                int m, parentGroupSize;
                multiplication mult;
                defaultMultiplication defMult;

        };
    private: 
        int n; 
        std::vector<A::B> elements;

};

#endif

A.cpp

#include "A.h"

#include <new>

A::A()
{

}

A::A(int n)
 : n(n), elements(std::vector<A::B>(n))
{

}

int A::defaultMultiply(int x, int y) { return (x * y); }
// special multiplication: integer groups have integer addition modulo the group size as their multiplication
int A::multiply(int x, int y)
{
    int a = x % this->n, b = y % this->n;
    if (a < 0) a += this->n;
    if (b < 0) b += this->n;
    return ((a + b) % n);
}

A::B::B()
 : m(0), 
    parentGroupSize(0), 
    mult(0),
    defMult(&A::defaultMultiply) // right?
{

}

A::B::B(int m, int n, multiplication mult)
 : parentGroupSize(n), mult(mult), defMult(0)
{
    // this->m must be in [0, g->size() - 1], if n is larger than 1
    if (n > 1)
    {
        this->m = m % n;
        if (this->m < 0) this->m = n + this->m;
    }
    else
    {
        this->m = m;
    }
}

A::B A::B::operator*(const A::B& b)
{
    if (this->parentGroupSize == b.parentGroupSize)
    {
        if (this->mult)
        {
            return A::B::B((this->*mult)(this->m, b.m), this->parentGroupSize, &A::B::mult); // I tried using this->mult for last argument, but it wouldn't take it
        }
    }
    return A::B(); // or something similar
}

int A::B::val() const { return this->m; }

的main.cpp

#include <iostream>

#include "A.h"

using namespace std;

int main()
{
    A(26);  // didn't implement any methods to get B's from A, since I am merely testing compilation. I'm trying for that ever-elusive MCVE with just this...
}

哦,我也收到以下错误:error: pointer to member type 'int (A::)(int, int)' incompatible with object type 'A::B'

1 个答案:

答案 0 :(得分:1)

您的问题不在于您将成员函数(作为参数)传递给与成员函数类类型不同的对象的构造函数;问题是你用错误的类型调用成员函数。您获得的编译器错误实际上非常清楚:指向成员的指针必须与声明它的相同类型(或派生类型)一起使用,否则这将毫无意义。

请注意,内部类不是派生的类; B对象不是 A的特殊类型。 (我想你已经意识到了这一点,但我想明确一点。)所以当你尝试用A类型的对象实例调用B的方法时,你已经要求提供的东西是完全没有意义。

所以,有两种选择:

  • 使用指向成员的B而非指向成员的指针A。从来没有任何理由使用A类型的对象调用成员,因此不清楚为什么你认为A指针成员在这里有用。
  • 使用非成员指针。请注意,您的defaultMultiplication类型已经 是非会员功能。请注意,非成员仍然可以将B的实例作为参数;他们只是有一个更简单的语法。