64,651
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
class test
{
public:
virtual void run() = 0;
virtual void prerun();
};
inline void test::run()
{
printf("test::fun()\n");
prerun();
}
void test::prerun()
{
run();
//some code here
}
class test_impl : public test
{
public:
virtual void run()
{
printf("test_impl::run()\n");
}
};
int main()
{
test *t = new test_impl();
t->prerun();
delete t;
return 0;
}
#include <stdio.h>
class test
{
public:
virtual void run() = 0;
/*virtual*/ void prerun(); //将virtual注释掉可能更清晰吧,也就是说不要覆盖prerun()
};
/*
我一直以为实现纯虚函数是不合法的,你竟然实现了还能正常编译,太不科学了
inline void test::run()
{
printf("test::fun()\n");
prerun();
}
*/
void test::prerun()
{
run(); //prerun()调用run,这个run因为是虚的,所以动态决定。
//some code here
}
class test_impl : public test
{
public:
virtual void run() //你这里实现了自己的run()
{
printf("test_impl::run()\n");
}
};
int main()
{
test *t = new test_impl();
t->prerun();//这里t虽然是基类test指针,但内部其实调用 test_impl 中你实现的run函数
//这样如果你有很多个继承test的子类test_implN,那么使用统一的代码t->prerun就能实现统一的功能。基本就是这用处。
delete t;
return 0;
}
我的理解都在注视中了。最后我感觉你俩函数名prerun和run是不是反了?