我是新来的C++编程,在做一些C++程序时我有一个疑问,那就是如何实现静态成员函数的动态绑定。正常成员函数的动态绑定可以通过将成员函数声明为虚拟来实现,但我们不能将静态成员函数声明为虚拟,所以请帮助我。并请参见下面的例子:静态成员函数继承
#include <iostream>
#include <windows.h>
using namespace std;
class ClassA
{
protected :
int width, height;
public:
void set(int x, int y)
{
width = x, height = y;
}
static void print()
{
cout << "base class static function" << endl;
}
virtual int area()
{
return 0;
}
};
class ClassB : public ClassA
{
public:
static void print()
{
cout << "derived class static function" << endl;
}
int area()
{
return (width * height);
}
};
int main()
{
ClassA *ptr = NULL;
ClassB obj;
ptr = &obj ;
ptr->set(10, 20);
cout << ptr->area() << endl;
ptr->print();
return 0;
}
在上面的代码中,我已指定派生类对象的指针和调用静态成员函数打印(),但它被调用基类功能,所以我怎样才能实现动态绑定静态成员函数。
不错!我喜欢。 –