gpt4 book ai didi

c++ - 如何在类定义中调用指针成员函数?

转载 作者:行者123 更新时间:2023-11-27 23:04:30 27 4
gpt4 key购买 nike

如何在类定义中调用指针成员函数?我的代码:

//Myclass.h

struct Booking{
int src;
int dest;
int pos;
};

class MyClass{
public:
void ExecutePlan();
private:
struct FlightPlan{
string name;
vector<Booking> bookings
};

typedef FlightPlan FP;
FP firstplan;
FP secondplan;
void FirstPlan(Booking& book);
void SecondPlan(Booking& book);
void Execute(FP& fplan, void (MyClass::*mptr)(Booking& book));
};

// Myclass.cpp
void MyClass::FirstPlan(Booking& book){
// do something with booking
}

void MyClass::SecondPlan(Booking& book){
// do something with booking
}

void MyClass::Execute(FP& fplan, void(MyClass::*mptr)(const FlightPlan& fp)){
for (int i=0; i<.fplan.bookings.size(); i++){
cout << "Executing Plan: "<< fplan.name << endl;

// Problematic line ...
mptr(bookings[i]); // <----- can't compile with this
}
}

void MyClass::Execute(){
// is this the correct design to call this member functions ???

Execute(firstplan, &MyClass::FirstPlan)
Execute(secondplan, &MyClass::SecondPlan)
}

我如何构造执行函数以接收成员函数作为指针?

请问:我是C++的新手,也许设计很奇怪!!

保罗

最佳答案

How to call pointer member function inside a class definition?

与成员名称不同,成员指针不会隐式应用于this。你必须明确:

(this->*mptr)(fplan.bookings[i]);

is this the correct design to call this member functions ???

除了一些明显的错误(例如缺少 ; ,在 const FlightPlan& 的定义中你指的是 Booking& Execute),其余代码看起来没问题。具体

Execute(firstplan, &MyClass::FirstPlan)   
Execute(secondplan, &MyClass::SecondPlan)

是获取成员函数指针的正确语法。

关于c++ - 如何在类定义中调用指针成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24574867/

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