C++ 如何在多态性中强制隐式转换? 请考虑这个例子, 如何在第二个参数是指向成员函数的指针的函数中强制隐式转换。 在函数的参数列表中显式转换不是我现在想要实现的。 相反,我希望编译器能像处理第一个参数一样 struct Base { virtual ~Base() = 0 {} }; struct Derived : public Base { void f(){} }; typedef void(Base::*polymorph)(); // how do I force IMPLICIT conversion here: EDIT: (polymorph type work only for polymorph pointer type no conversion) void func(Base* arg1, polymorph arg2) // void* arg2, (void*) arg2 etc... dosn't work { polymorph temp = reinterpret_cast<polymorph>(arg2); // to achive this } int main() { Derived* test = new Derived; // first parameter work but another gives an error func(test, &Derived::f); // BY NOT CHANGING THIS! delete test; return 0; } struct Base { 虚拟~Base()=0{} }; 结构派生:公共基 { void f(){} }; typedef void(基::*多晶型)(); //如何在此处强制隐式转换:编辑:(变形类型仅适用于变形指针类型无转换) void func(基*arg1,变形arg2)//void*arg2,(void*)arg2等。。。不行 { polymorph temp=reinterpret_cast(arg2);//要实现这一点 } int main() { 派生*测试=新派生; //第一个参数起作用,但另一个参数给出错误 func(test,&派生::f);//通过不更改此参数! 删除测试; 返回0; }

C++ 如何在多态性中强制隐式转换? 请考虑这个例子, 如何在第二个参数是指向成员函数的指针的函数中强制隐式转换。 在函数的参数列表中显式转换不是我现在想要实现的。 相反,我希望编译器能像处理第一个参数一样 struct Base { virtual ~Base() = 0 {} }; struct Derived : public Base { void f(){} }; typedef void(Base::*polymorph)(); // how do I force IMPLICIT conversion here: EDIT: (polymorph type work only for polymorph pointer type no conversion) void func(Base* arg1, polymorph arg2) // void* arg2, (void*) arg2 etc... dosn't work { polymorph temp = reinterpret_cast<polymorph>(arg2); // to achive this } int main() { Derived* test = new Derived; // first parameter work but another gives an error func(test, &Derived::f); // BY NOT CHANGING THIS! delete test; return 0; } struct Base { 虚拟~Base()=0{} }; 结构派生:公共基 { void f(){} }; typedef void(基::*多晶型)(); //如何在此处强制隐式转换:编辑:(变形类型仅适用于变形指针类型无转换) void func(基*arg1,变形arg2)//void*arg2,(void*)arg2等。。。不行 { polymorph temp=reinterpret_cast(arg2);//要实现这一点 } int main() { 派生*测试=新派生; //第一个参数起作用,但另一个参数给出错误 func(test,&派生::f);//通过不更改此参数! 删除测试; 返回0; },c++,inheritance,C++,Inheritance,尽可能干净。代码如下。但我不知道在实际调用“temp”时,将引用谁的“this”指针 typedef void(Base::*polymorph)(); void func(Base* arg1, polymorph arg2) { polymorph temp = arg2; } int main() { Derived* test = new Derived; // first parameter work but another gives an

尽可能干净。代码如下。但我不知道在实际调用“temp”时,将引用谁的“this”指针

typedef void(Base::*polymorph)(); 

void func(Base* arg1, polymorph arg2)
{ 
    polymorph temp = arg2;
} 


int main() 
{ 
    Derived* test = new Derived; 
    // first parameter work but another gives an error 
    func(test, static_cast<polymorph>(&Derived::f)); 
    delete test; 
    return 0; 
} 
typedef void(基::*polymorph)();
void func(基*arg1,变形arg2)
{ 
多晶型温度=arg2;
} 
int main()
{ 
派生*测试=新派生;
//第一个参数起作用,但另一个参数给出错误
func(测试、静态转换和派生::f));
删除测试;
返回0;
} 

我怀疑这是做不到的。在func中,您只知道(静态地)您正在处理一个基本对象,假装任何基本对象都有该方法是不安全的。-此外,仅仅因为涉及到一个指针,并不意味着您必须使用
new/delete
派生测试;func(&测试,&派生::f)