静态变量在静态方法中的基类和继承 [英] Static variables in static method in base class and inheritance

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

问题描述

我有这些C ++类:

  class Base 
{
protected:
static int method()
{
static int x = 0;
return x ++;
}
};

A类:public Base
{

};

class B:public Base
{

};

x 静态变量 A B ,或者每个人都有自己的 x c $ c> c $ c> c $ c> c $ c> c $ c> c $ c> c $ c> > x 。一个很好的解决方法是使用 CRTP

 模板< class Derived> 
class Base
{
protected:
static int method()
{
static int x = 0;
return x ++;
}
};

class A:public Base< A> {};
class B:public Base< B> {};

这将创建一个不同的 Base< T>



你可能还需要一个 Baser基因来保留多态性,如Neil和Akanksh所指出的。


I have these C++ classes:

class Base
{
protected:
    static int method()
    {
        static int x = 0;
        return x++;
    }
};

class A : public Base
{

};

class B : public Base
{

};

Will the x static variable be shared among A and B, or will each one of them have it's own independent x variable (which is what I want)?

解决方案

There will only be one instance of x in the entire program. A nice work-around is to use the CRTP:

template <class Derived>
class Base
{
protected:
    static int method()
    {
        static int x = 0;
        return x++;
    }
};

class A : public Base<A> { };
class B : public Base<B> { };

This will create a different Base<T>, and therefore a distinct x, for each class that derives from it.

You may also need a "Baser" base to retain polymorphism, as Neil and Akanksh point out.

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

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