64,654
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class A
{
public:
void dosth()
{
}
};
template <class T>
union B
{
T point;
void (*p)();
};
int main()
{
union B<void (A::*)()> change;
change.point=&A::dosth;
(change.p)();
return 0;
}
// file: csdn.cpp
// g++ csdn.cpp
#include <iostream>
class base_of_base {
public:
void foo(int i) {
std::cout << "base_of_base::foo(), i: " << i << std::endl;
}
};
class base : public base_of_base {
public:
explicit base(int i) : i_(i) {}
void bar() {
std::cout << "base::bar(), i_: " << i_ << std::endl;
}
virtual void go(std::string s) const = 0;
private:
int i_;
};
class derived : public base {
public:
explicit derived(int i)
: base(i) { }
virtual void go(std::string s) const {
std::cout << "derived::go(), s: " << s << std::endl;
}
};
void
call_go(const base &b) {
void (base::*fn_ptr3)(std::string) const = &base::go;
(b.*fn_ptr3)("3");
}
int
main() {
// case 1
void (derived::*fn_ptr)() = &base::bar;
derived d(1);
(d.*fn_ptr)();
// case 2
void (derived::*fn_ptr2)(int) = &base::foo;
derived d2(2);
(d2.*fn_ptr2)(2);
// case 3
derived d3(3);
call_go(d3);
return (0);
}
#include <iostream>
using namespace std;
class AClass
{
public:
int __cdecl func(int arg)
{
cout<<arg<<endl;
return 0;
}
};
typedef int (__cdecl *t_pf)(AClass *, int);//使用普通函数指针指向成员函数是要多1个参数,即this指针参数
t_pf convert(int other, ...)
{
return (t_pf)*(&other + 1);
}
int main()
{
AClass obj;
int i = 123;
t_pf pf = convert(i, &AClass::func);
obj.func(i);//使用对象调用成员函数
pf(&obj, i);//使用普通函数指针调用成员函数,注意这里的第一个参数就相当于this指针
system("pause");
return 0;
}
#include <iostream>
using namespace std;
class AClass
{
public:
int __cdecl func(int arg)
{
cout<<arg<<endl;
return 0;
}
};
typedef int (__cdecl *t_pf)(AClass *, int);//使用普通函数指针指向成员函数是要多1个参数,即this指针参数
t_pf convert(int (__cdecl AClass::*)(int))
{
t_pf i;
__asm
{
mov eax, [ebp + 8]
mov [i], eax
}
return i;
}
int main()
{
AClass obj;
int i = 123;
t_pf pf = convert(&AClass::func);
obj.func(i);//使用对象调用成员函数
pf(&obj, i);//使用普通函数指针调用成员函数,注意这里的第一个参数就相当于this指针
system("pause");
return 0;
}
#include <iostream>
using namespace std;
class AClass
{
public:
int __cdecl func(int arg)
{
cout<<arg<<endl;
return 0;
}
};
typedef int (__cdecl *t_pf)(AClass *, int);//使用普通函数指针指向成员函数是要多1个参数,即this指针参数
int (__cdecl AClass::*pf_AClass)(int) = &AClass::func;//定义成员函数指针pf_AClass指向func函数
t_pf pf = *(t_pf *)&pf_AClass;//此处将pf_AClass强制转换为t_pf类型
int main()
{
AClass obj;
int i = 123;
obj.func(i);//使用对象调用成员函数
(obj.*pf_AClass)(i);//使用成员指针调用成员函数
pf(&obj, i);//使用普通函数指针调用成员函数,注意这里的第一个参数就相当于this指针
system("pause");
return 0;
}
class Foo
{
public:
double One(long inVal);
double Two(long inVal);
};
void main(int argc, char **argv)
{
double (Foo::*funcPtr)(long) = &Foo::One;
Foo aFoo;
double result = (aFoo.*funcPtr)(2);
return 0;
}