如何声明两个不同的静态变量? (C ++)
-
14-09-2019 - |
题
编辑:声明它们私有是一个错字,我固定它:
与另一个问题,如果我声明在一个类中的静态变量,然后从该衍生的一类,是否有任何方式来声明静态变量按每个类个体。即:
class A:
{
public:
static int x;
};
class B:A
{
public:
const static int x;
};
这是否定义两个不同的静态变量x
,一个A和一个B,否则我会得到一个错误重新定义x
,如果我得到一个错误,怎么做我创建两个单独的静态变量?
解决方案
当你使用静态变量,它可能是一个好主意,称他们明确:
public class B:A
{
public const static int x;
public int foo()
{
return B::x;
}
}
这样一来,即使类“上面”层次结构中的你决定创建一个类似命名的成员,它不会破坏你的代码。同样地,我通常访问正常构件字段时尝试我们this
关键字。
<强>更新以使用C ++的语法。
其他提示
这产生两个单独的静态变量。
请注意,您已经隐含声明这些私人:
class A:
{
private:
static int x;
};
class B:A
{
private:
const static int x;
};
这意味着变量不是相互竞争。
正如已经说过的,创建两个单独的变量:
A::x;
// and
B::x;
在事实上,如果你尝试,直到你更精确的使用是“x”在B的方法中,只有较近范围定义将被使用:
#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
有人提到,无障碍设施可能限制访问性:使基私有变量不会使它的子类访问。 但是,如果变量已被保护的或公共的,使用一个明确的访问方法还是要靠我刚刚展示了当地的范围规则。
如果你想有一个静态变量,它是个人每个类使用一个 - 你可以使用一个模板类结果。 对于如
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'
};
不隶属于 StackOverflow