关于另一个问题,如果我在类中声明了一个静态变量,然后从中派生了一个类,有没有办法将静态变量声明为每个类的个体。即:
class A:
{
public:
static int x;
};
class B:A
{
public:
const static int x;
};
是否定义了两个不同的静态变量x
,一个用于A,一个用于B,或者我会因重新定义x
而出错,如果我确实收到错误,我该怎么办?创建两个单独的静态变量?
答案 0 :(得分:2)
当您使用静态变量时,明确引用它们可能是个好主意:
public class B:A
{
public const static int x;
public int foo()
{
return B::x;
}
}
这样,即使层次结构中的“上面”类决定创建一个类似命名的成员,它也不会破坏您的代码。同样,我通常会在访问普通成员字段时尝试使用this
关键字。
已更新以使用C ++语法。
答案 1 :(得分:1)
这会创建两个独立的静态变量。
答案 2 :(得分:0)
请注意,您已隐式声明这些私有:
class A:
{
private:
static int x;
};
class B:A
{
private:
const static int x;
};
这意味着变量不会相互竞争。
答案 3 :(得分:0)
如前所述,这会产生两个独立的变量:
A::x;
// and
B::x;
事实上,如果你试图在B的方法中只使用'x',那么在你更精确之前,只会使用更近的范围定义:
#include <iostream>
class A
{
protected:
static int x;
public:
A() { x = 7; }
};
int A::x = 22;
class B:A
{
static const int x = 42;
public:
int a_x() const { return A::x; }
int b_x() const { return B::x; }
int my_x() const { return x; } // here we get the more local variable, that is B::x.
};
int main()
{
B b;
std::cout << "A::x = " << b.a_x() << std::endl;
std::cout << "B::x = " << b.b_x() << std::endl;
std::cout << "b's x = " << b.my_x() << std::endl;
std::cin.ignore();
return 0;
}
输出:
A::x = 7
B::x = 42
b's x = 42
有人提到可访问性可能会限制可访问性:将基本变量设为私有不会使子类可以访问它。 但是,如果变量必须受到保护或公开,请使用显式访问方法或依赖我刚才演示的本地范围规则。
答案 4 :(得分:0)
如果您想要一个与使用A的每个类相对应的静态变量 - 您可以使用模板类 对于例如
template<class T> struct A
{
A() { ++s_var; }
static int s_var;
};
template<class T> int A<T>::s_var;
stuct B :A<B> {
B() { ++s_var; } // this is a different s_var than the one used by 'C' below
};
struct C : A<C> {
C() { ++s_var; } // this is a different s_var than the one used by 'B'
};