C++里,基类的静态变量子类能共享吗,为了验证这个问题这里写了一段代码进行测试:
#include <iostream>class Base {
public:static int staticVariable;
};class Derived : public Base {
};int Base::staticVariable = 10;int main() {Base::staticVariable = 20;std::cout << "Base::staticVariable: " << Base::staticVariable << std::endl;std::cout << "Derived::staticVariable: " << Derived::staticVariable << std::endl;Derived::staticVariable = 30;std::cout << "Base::staticVariable: " << Base::staticVariable << std::endl;std::cout << "Derived::staticVariable: " << Derived::staticVariable << std::endl;return 0;
}
在这个代码中,定义了一个基类 Base,其中有一个静态变量 staticVariable。然后定义了一个子类 Derived,它继承了 Base。在 main 函数中,我们分别修改静态变量的值并访问 Base::staticVariable 和 Derived::staticVariable。
输出结果如下:
Base::staticVariable: 20
Derived::staticVariable: 20
Base::staticVariable: 30
Derived::staticVariable: 30
可以看到,修改了 Base::staticVariable 或 Derived::staticVariable 的值,它们仍然是相互影响,所以基类和子类的静态变量是共享的。