Static Virtual functions in c++

2019-03-25 00:59发布

I have a base class and a derived one and I want to change base functions while keeping them static as they should be passed to other functions as static.

How can I do that?

7条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-25 01:20

You cannot have static virtual functions, because it doesn't make sense to have them.

查看更多
祖国的老花朵
3楼-- · 2019-03-25 01:24

static function can not be virtual since they do not have an instance through which they are accessed. I do believe you can overwrite them though.

查看更多
再贱就再见
4楼-- · 2019-03-25 01:27

If i am correct in understanding ur question, then u can follow the following approach otherwise ignore..

have static function pointer in the base class.

in base class have a static function ( in which u call the function by using that static function pointer)..

in derived classes set that static function poiter to the function defination u wish to execute.. ( in base class u can set the function pointer to some default function).

查看更多
Viruses.
5楼-- · 2019-03-25 01:30

You can't have static virtual functions in C++.

查看更多
▲ chillily
6楼-- · 2019-03-25 01:39

The ATL framework gets around the limitation of no virtual statics by making the base class be a template, and then having derived classes pass their class type as a template parameter. The base class can then call derived class statics when needed, eg:

template< class DerivedType >
class Base
{
public:
  static void DoSomething() { DerivedType::DoSomethingElse(); }
};

class Derived1 : public Base<Derived1>
{
public:
  static void DoSomethingElse() { ... }
};

class Derived2 : public Base<Derived2>
{
public:
  static void DoSomethingElse() { ... }
};

This is known as Curiously recurring template pattern, which can be used to implement static polymorphism.

查看更多
We Are One
7楼-- · 2019-03-25 01:42

Virtual functions typically rely on this pointer to determine the type of function to be called at run time.

A static member function does not pass a this so static virtual functions are not allowed in C++.

查看更多
登录 后发表回答