静态变量继承C ++ [英] Static variable inheritance C++

查看:95
本文介绍了静态变量继承C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要派生类中的静态变量,所以我想在基类中做一些事情.基类将是虚拟的.有可能吗?

I want static variables in derived classes, so I want to make some stuff in a base class. Base class would be virtual. Is it possible?

class Base {
public:
    static const int x;
    void f() {
        return x;
    }
    virtual void g() = 0;
};

class Derived1 : virtual Base {
public:
    void g() {}
};
const int Derived1::x = 1;

class Derived2 : virtual Base {
public:
    void g() {}
};
const int Derived2::x = 2;

...

Derived1 a;
Derived2 b;
a.f() == 1; // should be true
b.f() == 2; // should be true

推荐答案

A,不,C ++没有虚拟静态函数.您可以做的是使用非静态的getter方法:

Alas, no, C++ has no virtual statics. What you can do instead is use a non-static getter method:

 class A {
      virtual const int& Foo() const = 0;
 }

 class B : A {
      static int foo_;
      const int& Foo() const override { return foo_; }
 }
 int B::foo_ { 1 };

您可以使用定义的混合类来自动化"此操作使用 CRTP :

You can "automate" this with a mix-in class defined using CRTP:

 class A {
      virtual const int& Foo() const = 0;
 }

 template <typename T>
 class FooHolder {
      static int foo_;
      const int& Foo() const override { return foo_; }
 }

 class B : A, virtual FooHolder<B> {
      // other stuff
 }

这样,您在子类中唯一需要做的就是指示混合继承.我可能在这里缺少一些虚拟继承警告(因为我很少使用它).

This way, the only thing you need to do in a subclass is also indicate the mix-in inheritance. There might be some virtual inheritance caveats I'm missing here (as I rarely use it).

另一种方法(在此处中进行了描述)是使类A本身成为模板,以便每个B都继承自A.但这会破坏您的继承结构.

Another option, described here, is to make class A templated itself, so that each B inherits from a different A. But that will break your inheritance structure.

这篇关于静态变量继承C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆