基类的静态成员函数可以调用其派生类对象吗? (C ++)

时间:2011-01-10 07:00:04

标签: c++

基类的静态成员函数可以调用其派生类对象吗?

3 个答案:

答案 0 :(得分:3)

static成员函数视为一些非成员函数。是的无论非成员函数可以做什么,static成员函数都可以做同样的事情!

答案 1 :(得分:1)

是的,虽然有两件事需要注意。

第一个是前向引用。如果静态方法的代码在.cpp文件中,那么您应该能够安全地#include基类和派生类头。

<Base.h>
class Base
{
protected:
    Base();
public:
    virtual ~Base();

    static Base* Create();
};

<Derived.h>
#include "Base.h"
class Derived : public Base
{
public:
    Derived(int aParameterGoesHere);
};

<Base.cpp>
#include "Base.h"
#include "Derived.h"

Base::Base() { }
Base::~Base() { }

Base* Base::Create()
{
    return new Derived(42);
}

要注意的第二件事是Derived的私人/受保护成员无法从Base访问,除非他们被声明为BaseBase的虚拟成员宣布了Derived的朋友类(考虑到紧密耦合,这不是不合理的):

<Derived.h>
#include "Base.h"
class Derived : public Base
{
    friend Base;
private:
    Derived(int aParameterGoesHere);
};

答案 2 :(得分:1)

不,它无法调用,因为静态成员函数没有为其分配对象,因此它没有派生类对象。

但是,您可以使用CRTP,如下所示:

template< T >
struct base
{
  base()
  {
    T::foo();   // here calling a static method of derived class
  }
  virtual ~base(){}
};

struct A : base< A >
{
  virtual ~A(){}
  static void foo()
  {
    // do stuff
  }
};
相关问题