【发布时间】:2015-12-22 14:13:03
【问题描述】:
我尝试通过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->, braces, *, ->, . 的任何组合,它都不起作用。
有什么想法吗? 谢谢!
【问题讨论】:
标签: c++ struct function-pointers member-function-pointers