我有这些 C++ 类:
class Base
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base
{
};
class B : public Base
{
};
x
静态变量会在 and 之间共享,A
还是B
每个人都有自己的独立x
变量(这是我想要的)?
我有这些 C++ 类:
class Base
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base
{
};
class B : public Base
{
};
x
静态变量会在 and 之间共享,A
还是B
每个人都有自己的独立x
变量(这是我想要的)?
x
整个程序中只有一个实例。一个很好的解决方法是使用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> { };
这将为从它派生的每个类创建一个不同Base<T>
的,因此是不同的。x
正如 Neil 和 Akanksh 指出的那样,您可能还需要一个“Baser”基来保留多态性。
只有一个,由所有三个班级共享。如果您想要单独的实例,则必须在派生类中创建单独的函数。
我很确定它将在 A 和 B 之间共享。
如果您想要独立变量,您可以使用“Curiously Recurring Template Pattern”,例如:
template<typename Derived>
class Base
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base<A>
{
};
class B : public Base<B>
{
};
当然,如果你想要多态性,你将不得不定义一个 Base 派生自的偶数“Baser”类,这Base<A>
与Base<B>
类似:
class Baser
{
};
template<typename Derived>
class Base : public Baser
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base<A>
{};
class B : public Base<B>
{};
现在 A 和 B 也可以是多态的。
前者。局部静态变量绑定到包含它们的方法,并且method
存在于所有子类的一个化身中(实际上,对于整个应用程序,即使程序的其余部分看不到该方法)。
变量将被共享 - 它是每个函数的 - 在这种情况下,它所属的函数是Base::method()
. 但是,如果class Base
是模板类,您将为模板的每个实例化(每个唯一的实际模板参数集)获得一个变量实例class Base
- 每个实例化都是一个新函数。
如果您将 X 设为静态,那么它将在所有子类之间共享。函数是静态的没有问题。