C++笔记2:基类的静态变量子类能共享吗

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 的值,它们仍然是相互影响,所以基类和子类的静态变量是共享的

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值