[英]array of pointers to member functions: make it work
In the following code I am getting the error: 在以下代码中,我得到了错误:
a value of type (double*)(const double& arg) const cannot be assigned to an entity of type pt2calculateA
Any suggestions on how to make it work? 关于如何使其工作的任何建议?
class myClass {
private:
typedef double (*pt2calculateA)(double);
pt2calculateA calculateA[2];
public:
myClass () {
calculateA[0] = &calculateA1; //->error
calculateA[1] = &calculateA2; //->error
}
double calculateA1(const double& arg) const {
...
}
double calculateA2(const double& arg) const {
...
}
}
myClass::calculateA1()
is not a function ; myClass::calculateA1()
不是函数 ; rather, it is a member function . 而是一个成员函数 。 So the types are naturally not compatible.
因此,这些类型自然是不兼容的。
The type of &myClass::calculcateA1
is double (myClass::*)(const double &) const
, which is a pointer-to-member-function (PTFM). &myClass::calculcateA1
的类型为double (myClass::*)(const double &) const
,它是成员函数指针(PTFM)。 Note that you can only use a PTMF together with a pointer to an object instance (ie a myClass*
). 请注意,您只能将PTMF与指向对象实例的指针(即
myClass*
)一起使用。
If you change your typedef, you could at least store the pointers correctly: 如果更改typedef,则至少可以正确存储指针:
typedef double (myClass::*pt2calculateA)(const double &) const;
You'll have to say &myClass::calculateA1
, etc., to take the address. 您必须说
&myClass::calculateA1
等以获取地址。
In C++11, you can initialize the array in the initializer list: 在C ++ 11中,您可以在初始化列表中初始化数组:
myClass() : calculateA{&myClass::calculateA1, &myClass::calculateA2} { }
Try this: 尝试这个:
class myClass {
private:
typedef double (myClass::*pt2calculateA)(const double&) const;
pt2calculateA calculateA[2];
public:
myClass () {
calculateA[0] = &myClass::calculateA1;
calculateA[1] = &myClass::calculateA2;
}
double calculateA1(const double& arg) const {
// ...
}
double calculateA2(const double& arg) const {
// ...
}
};
Not only the parameter type differs between the typedef and the actual functions, but also one is a function pointer while the other is a member function pointer. 在typedef和实际函数之间,不仅参数类型有所不同,而且一个是函数指针,而另一个是成员函数指针。
myClass::calculateA1
has type double (myClass::*)(const double& arg) const
. myClass::calculateA1
具有double (myClass::*)(const double& arg) const
类型double (myClass::*)(const double& arg) const
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.