指向成员函数的指针 [英] Pointers to a member function

查看:66
本文介绍了指向成员函数的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码(忽略标头和类型):

Here''s my code (ignoring headers and the types):

class A {
public:
    A(); //constructor
    memberfunc1();
    memberfunc2();
};

class B : A
{ //ie inherits from base class A
public:
    B()
    {
        A *pA = new A[3]; //ok so ive got 3 A objects with pointer to them pA right? wrong?
    };
}

main()
{
    B * pB = new B[2]; // creates 2 B objects each containing 3
}


一切正常,但是我不确定该怎么做:
1.我想确定对象A [0]要执行memberfunction1
2.我想使对象A [1]和A [2]成为memberfunction2

这可能吗?另外,请您能解释一下我声明的两个指针实际指向什么?我原本以为他们只是声明自己为指向类的指针,然后可以指向这些类.这是正确的吗?他们做了我想要的,但是我不确定为什么...以及当我尝试做* pB-> memberfunc1;时.它搞砸了错误...请随时编写其他示例代码.我只是想获得理解,而我在网上找到的所有内容都与单个对象有关-而不是它们的数组.非常感谢!


This all works fine but I''m unsure what to do for the following:
1. I want to determine the object A[0] to do memberfunction1
2. I want to make objects A[1] and A[2] do memberfunction2

Is this possible? Also, please can you explain what the two pointers I declared actually point to? I origionally thought they just declared themselves as pointers to the classes which could then point onwards. Is this right? They do what I wanted but I am uncomfortable in the uncertainty of why... and when I try to do *pB->memberfunc1; it messes up with errors... Please feel free to make a different example code. I just want to get the understanding and everything I find online is to do with a single object - not an array of them. Many thanks!

推荐答案

这是否有助于消除您的困惑?

Does this help clear up your confusion?

#include <stdio.h>
#include <stdlib.h>

class A {
public:
    A() {}; //constructor
    void memberfunc1(){printf("A:memberfunc1\n");}
    void memberfunc2(){printf("A:memberfunc2\n");}
};

class B : public A
{ //ie inherits from base class A
    A *pA;
public:
    B()
    {
        pA = new A[3]; //ok got an array holding 3 instances of class A
    };
    ~B()
    {
        delete [] pA;     // we don't want the memory any more since this is the destructor. Giv the mem back
    }

    void showAll()
    {
        int i;
        for (i=0; i<3; i++)
        {
            printf("-------- Callling member functions of pA[%d]--------\n", i);
            pA[i].memberfunc1();
            pA[i].memberfunc2();
        }
    }
};

int main()
{
    B *pB = new B[2]; // creates 2 B objects each containing 3

    printf("=======***** Calling member function of pb[0] ****=======\n");
    pB[0].showAll();
    printf("=======***** Calling member function of pb[1] ****=======\n");
    pB[1].showAll();

    delete [] pB;       // we allocated mem, so we have to free it too, since they're allocated on the heap
}



另外,为解决您的问题:

这可能吗? (A [0]调用memberfunction1,A [1]和A [2]调用memberfunction2)
当然可以,编译代码然后旋转一下.

这两个指针实际上指向什么?
它们不过是指向数组中第一个元素的指针.由于它们(数组)的声明方式,编译器不知道每个数组中有多少个元素.

请考虑以下代码段:



Also, to address your questions:

Is this possible? ( A[0] call memberfunction1, A[1] & A[2] call memberfunction2)
Sure is, compile the code and give it a whirl.

What do these two pointers actually point to?
They''re no more than a pointer to the first element in the array. Because of the way they''re (the arrays) declared, the compiler doesn''t know how many elements are in each array.

Consider the following snippet:

char str1[] = "This is a 24 char string";
char *str2 = strdup(str1);
char *str3 = new char[strlen(str1)+1];
strcpy(str3, str1);
printf("sizeof(str1) = %d\n", sizeof(str1) );
printf("sizeof(str2) = %d\n", sizeof(str2) );
printf("sizeof(str3) = %d\n", sizeof(str3) );


输出:


Output:

sizeof(str1) = 25
sizeof(str2) = 4
sizeof(str3) = 4



您需要谨慎对待这些结果的解释-虽然所有这三个都是指针,但sizeof运算符的行为确实在某种程度上使水变得混乱.我不会尝试解释,因为害怕使它们变得更加晦暗..


希望这有助于缓解,而不是加剧您的困惑. :)



You need to be careful with how you interpret these results - while it''s true that all three of them are pointers, the behaviour of the sizeof operator muddies the water somewhat. I won''t try to explain, for fear of making them even murkier..


Hope this helps alleviate, rather than adding to your confusion. :)


只是为了消除误解,而这种误解在本来很好的解决方案1中没有解决:

当您在类中声明成员函数时,这不是函数指针!而且您不能原样使用它.这就是为什么成员函数(也许更恰当地)称为方法"的原因.相反,这样的声明与简单的(全局)函数声明几乎相同:只是一个定义函数签名的原型,其中包含有关如何从其他地方调用它的足够信息.
Just to clear up a misunderstanding that isn''t covered in the otherwise excellent solution 1:

When you declare a member function in a class, this is not a function pointer! And you cannot use it as such. That is why a member function is - perhaps more appropriately - called a ''method''. Instead, such a declaration is pretty much the same as a simple (global) function declaration: just a prototype that defines the signature of the function, with enough information on how to call it from elsewhere.

// example 1: global variable
int v;
// example 2: global function declaration
void global_func1(int x); // only signature here
// example 3: global function declaration and implementation combined
int get() {
   return v;
}

// implementation for example 2:
// (this may be moved anywhere in your code)
void global_func1(int x) {
   v = x;
}

class A {
private: // declare the following as restricted; may only be used 'inside' the class
   // example 4: member variable
   int value;    // declaration of a 'private' member variable
public:  // declare the follwing as accessible from anywhere
   // example 5: member function declaration
   void member_func(int x);
   // example 3: member function signature and implementation combined
   int get() const {
      return value; // note that the 'private' variable value can be accessed here
   }
};

// implementation for example 5:
void A::member_func(int x) {
   value = x; // note that the 'private' variable value can be accessed here
}


int main() {
   // ex. 1: access global variable
   v = 7;
   // ex. 2: call global function
   global_func(3); // sets v to 3
   // ex. 3: call other global function
   int x = get(); // sets x to 3

   A a[3]; // defines array of 3 objects of type 'class A'
   // ex. 4: accessing member variable - this is not possible here!
   // ...
   // ex. 5: call member function, on different objects
   a[0].member_func(4); // call the function, using first object
                        // now a[0].value is equal to 4
   a[1].member_func(5); // call function on second object ...
                        // now a[1].value is equal to 5, while a[0].value is still 4
   a[2].member_func(6); // ... and on third object
                        // a[2].value is now 6
   // ex. 6: call other member function
   int y = a[1].get(); // sets y to 5
   int z = a[2].get(); // sets z to 6

   return 0;
}


您可以看到有关成员函数的各种信息:
1.调用成员函数(通常)需要一个您称之为"on"的对象
2.它不涉及函数指针
3.调用成员函数可以修改被调用对象的状态,并且仅修改该对象的状态-其他对象不受影响.
4.相比之下,全局函数将/将始终仅影响全局状态(即全局变量)


You can see various things about member functions:
1. calling a member function (usually) requires an object that you call it ''on''
2. it doesn''t involve function pointers
3. calling a member function may modify the state of the object it is called on, and only of that object - other objects are unaffected.
4. In comparison, a global function will/can always affect the global state only (i. e. global variables)


这篇关于指向成员函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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