gpt4 book ai didi

c++ - C++中指向成员函数的指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:38:26 25 4
gpt4 key购买 nike

这实际上是一个国际象棋下棋程序,但是代码太长无法贴在这里,所以我将使用一个更简单的无关示例:

假设我有这样一个对象:

class A{
int x1;
int x2;
public:
int Average(){ return (x1+x2)/2; }
};

我想要一个名为 AveragesList 的 vector ,它存储每个对象的所有 x1 和 x2 值的所有平均值(或指向它们的指针)。所以我尝试这样做:

vector<int>* AveragesList;

class A{
int x1;
int x2;
public:
int Average(){ return (x1+x2)/2; }
A(){ AveragesList.push_back(this->Average); } //trying to add pointer to member function Average() to AveragesList
};

但是当我尝试这样做时,我收到一条消息说“指向绑定(bind)函数的指针只能用于调用函数”。有解决办法吗?我不想简单地将 x1 和 x2 的平均值放在 AveragesList 中,因为如果 x1 或 x2 发生变化,AveragesList 中的值不会。另外,我的书说不要在 C++ 类中使用公共(public)变量,所以我不确定是否应该使用一个。

最佳答案

在 C++11 之前的 C++ 中没有处理闭包的内置方法,因此在不使用诸如 boost 之类的库的情况下解决该问题的最简单方法如下:定义一个名为 average,以及您的 x1x2 变量。在创建对象时将平均值设置为正确的值,并在每次 x1x2 更改时更新它。将指针存储在列表中,并使用它来访问平均值。

这不如即时计算结果好。如果您使用的是 C++11,则可以使用更好的解决方案:

#include <iostream>
#include <vector>
#include <functional>

class A{
int x1;
int x2;
public:
A(int _x1, int _x2) : x1(_x1), x2(_x2) {}
int Average(){ return (x1+x2)/2; }
void setX1(int _x1) { x1 = _x1; }
void setX2(int _x2) { x2 = _x2; }
};

using namespace std;

int main() {
vector<std::function<int()>> v;
A a1(1, 5);
A a2(2, 8);
v.push_back([&]{return a1.Average();});
v.push_back([&]{return a2.Average();});
for (int i = 0 ; i != v.size() ; i++) {
cout << v[i]() << endl;
}
a1.setX1(7);
a2.setX2(32);
for (int i = 0 ; i != v.size() ; i++) {
cout << v[i]() << endl;
}
return 0;
}

关于c++ - C++中指向成员函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10826677/

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