指向成员函数语法的指针 [英] Pointer to member function syntax

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

问题描述

我试图把头放在成员函数的指针周围,并被这个示例所困扰:

I'm trying to wrap my head around pointers to member functions and am stuck with this example:

#include <iostream>

class TestClass {
  public:
    void TestMethod(int, int) const;
};

void TestClass::TestMethod(int x, int y) const {
  std::cout << x << " + " << y << " = " << x + y << std::endl;
}

int main() {
  void (TestClass::*func)(int, int) const;
  func = TestClass::TestMethod;

  TestClass tc;
  tc.func(10, 20);

  return 0;
}

我认为代码应该做什么:

What I think the code should do:

  • 在main的第一行中,我声明一个指向class TestClass成员函数的指针,该成员函数不返回任何内容/采用两个int并被声明为const,称为 func .
  • 第二行将成员函数TestMethod(属于类TestClass)分配给func,这满足这些条件.
  • 第四行创建一个名为 tc TestClass对象.
  • 第五行尝试在TestClass-对象tc上调用func指向的成员函数.
  • In the first line of main I declare a pointer to a member function of class TestClass, which returns nothing/takes two int's and is declared const, called func.
  • The second line assigns the member-function TestMethod (of class TestClass) to func, which satisfies these criteria.
  • The forth line creates an TestClass-object called tc.
  • The fifth line tries to call the member function pointed to by func on the TestClass-object tc.

我遇到两个编译错误:

  • 而不是将TestClass::TestMethod分配给func.编译器尝试调用TestClass::TestMethod(即使不是static,因此也会引发错误):

  • Instead of assigning TestClass::TestMethod to func. The compiler tries to call TestClass::TestMethod (even though it's not static, therefore throws an error):

testPointerToMemberFunc.cpp:14:21: error: call to non-static member function without an object argument
  func = TestClass::TestMethod;
         ~~~~~~~~~~~^~~~~~~~~~

  • 编译器尝试在tc上调用名为func的函数,而不是调用func指向的函数.在我看来,好像func的声明方式不正确(作为指向成员函数的指针):

  • The compiler tries to call a function named func on tc, instead of the function, pointed to by func. To me this seems, like func isn't declared the right way (as a pointer to a member function):

    testPointerToMemberFunc.cpp:17:6: error: no member named 'func' in 'TestClass'
      tc.func(10, 20);
      ~~ ^
    

  • 我在做什么错了?

    推荐答案

    简单的语法细节.

    func = &TestClass::TestMethod;
    //     ^ Missing ampersand to form a pointer-to-member
    
    TestClass tc;
    (tc.*func)(10, 20);
    // ^^ Using the dot-star operator to dereference the pointer-to-member,
    // while minding its awkward precedence with respect to the call operator.
    

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

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