gpt4 book ai didi

c++ - 方法指针的问题

转载 作者:行者123 更新时间:2023-11-30 00:39:21 25 4
gpt4 key购买 nike

我刚刚学习 C++,但在方法指针方面遇到困难。比方说:

class One {
public:
int Add (int a, int b) {return a+b;}
};

typedef int (One::*pAdd) (int, int);

class Other {
public:
int Next (pAdd funct, int c){ return funct (c, 1);}

};

int main (){

One one;
Other other;

other.Next(one.Add, 2);

return 0;
}

正如我的 MinGW 所报告的,我有很多问题。首先,我没有正确调用 funct,因为编译器坚持使用 .* 或 ->* 。不知道如何合并此请求,欢迎提供任何帮助。现在,我可以通过使方法静态化以使用 C 样式指针或传递对象并从 Next 中调用方法来解决我的问题,但我想了解指向方法的指针。基本上,我很困惑为什么 one.Add 不是可接受的输入。要调用的方法已明确定义 (.Add) 并符合我的类型定义。另外,我从 typedef 中提供了类(一)的实例,从而提供了执行方法的上下文。但是编译器输出看起来我不仅错过了语法,而且我错过了这个概念。那么,如何将指针作为单个参数传递给以对象作为上下文的方法?

最佳答案

这里的主要问题是成员函数不与对象实例关联,它们只是签名略有不同的函数指针。

因此,当您想要调用成员函数时,您需要两件事:一个指向成员函数的指针 和调用它的对象实例

我稍微更改了您的代码示例:

#include <iostream>

class One {
public:
int Add (int a, int b) {return a+b;}
};

typedef int (One::*pAdd) (int, int);

class Other {
public:
int Next (One one, pAdd funct, int c){
return (one.*funct)(c, 1);
}
};

int main (){
One one;
Other other;

std::cout << other.Next(one, &One::Add, 2) << std::endl;

return 0;
}

it works现在。它可能会有所改进,但我认为您可以从这里开始。

我建议您阅读 Pointers to member functionsc++ faq lite ,这很好地解释了这一点。

关于c++ - 方法指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8991766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com