C++ C++;从类外部设置指向结构中函数成员的指针
我试图通过方法C++ C++;从类外部设置指向结构中函数成员的指针,c++,struct,function-pointers,member-function-pointers,C++,Struct,Function Pointers,Member Function Pointers,我试图通过方法SetPtr()从类外部设置类内str结构中包含的函数指针 我得到一个错误:非静态成员函数的使用无效 class C { public: float v1, v2; struct S { float (*Read)(); void (*Write)(float); } str; float ReadV1() { return v1; } void WriteV1(flo
SetPtr()
从类外部设置类内str结构中包含的函数指针
我得到一个错误:非静态成员函数的使用无效
class C {
public:
float v1, v2;
struct S {
float (*Read)();
void (*Write)(float);
} str;
float ReadV1() {
return v1;
}
void WriteV1(float value) {
v1 = value;
}
float ReadV2() {
return v2;
}
void WriteV2(float value) {
v2 = value;
}
void SetPtr(float (*read)(), void (*write)(float)) {
str.Read = read;
str.Write = write;
}
void F()
{
float f = str.Read();
str.Write(f);
}
};
int main()
{
C c;
c.SetPtr(c.ReadV1, c.WriteV2); // ERROR
c.v1 = 0;
c.F();
return 0;
}
我还尝试用指向成员函数的指针替换函数指针:
class C {
public:
float v1, v2;
struct S {
float (C::*Read)();
void (C::*Write)(float);
} str;
float ReadV1() {
return v1;
}
void WriteV1(float value) {
v1 = value;
}
float ReadV2() {
return v2;
}
void WriteV2(float value) {
v2 = value;
}
void SetPtr(float (C::*read)(), void (C::*write)(float)) {
str.Read = read;
str.Write = write;
}
void F()
{
float f = str.Read(); // ERROR
str.Write(f); // ERROR
}
};
int main()
{
C c;
c.SetPtr(&C::ReadV1, &C::WriteV2);
c.v1 = 0;
c.F();
return 0;
}
但这将在类中移动错误:
错误:必须使用“.”或“->”来调用中成员函数的指针
“((C*)this)->C::str.C::S::Read(…)”,例如,“(…->”*
((C*)this)->C::str.C::S::Read)(…)'
无论是this->,大括号,*,->,的组合是什么。
有什么想法吗?
谢谢 您需要使用第二种形式(带有指向类方法的指针),但在调用需要使用的方法时:
float f = (this->*str.Read)();
(this->*str.Write) (f);
第一个方法无法工作,因为指向类方法的指针不会衰减为指向标准函数的指针(即float(C::*)()
不能衰减为float(*)(
)
使用C++11
可以将方法存储为std::function
并使用std::bind
:
#include <functional>
class C {
struct S {
std::function <float()> Read ;
std::function <void(float)> Write ;
} str ;
void SetPtr(float (C::*read)(), void (C::*write)(float)) {
str.Read = std::bind(read, this);
str.Write = std::bind(write, this, std::placeholders::_1);
}
void F() {
float f = str.Read();
str.Write (f);
}
}
int main () {
C c;
c.SetPtr(&C::ReadV1, &C::WriteV2);
}
#包括
C类{
结构{
函数读取;
函数写入;
}str;
void SetPtr(float(C:::*读)(),void(C:::*写)(float)){
str.Read=std::bind(Read,this);
str.Write=std::bind(Write,this,std::占位符::_1);
}
void F(){
float f=str.Read();
str.Write(f);
}
}
int main(){
C C;
c、 SetPtr(&c::ReadV1,&c::WriteV2);
}