c++中的继承与静态成员

如果基类定义了一个静态成员,则在整个继承体系中只存在该成员的唯一定义。不论从基类中派生出多少个派生类,对于每个静态成员来说都只存在唯一的实例。

                                                                                ---《C++ Primer》

通过下面的例子可以直观地领会这一点:

#include <iostream>

class Base{
public:
    static void static_mem() {
        std::cout << "hello static mem" << std::endl;
    }
    static int x;
};
int Base::x = 0;

class Drived : public Base{
public:
    void f(const Drived& d){
        Base::static_mem();
        Drived::static_mem();
        d.static_mem();
        static_mem();
    }
    void print_data_mem_address(const Drived& d){
        std::cout << &(Base::x) << std::endl;
        std::cout << &(Drived::x) << std::endl;
        std::cout << &(d.x) << std::endl;
        std::cout << &x << std::endl;
    }
};

int main() {
    Drived d1;
    Drived d2;
    d1.f(d2);
    d1.print_data_mem_address(d2);
    return 0;
}
$ g++ -std=c++11 main.cpp
$ ./a.out 
hello static mem
hello static mem
hello static mem
hello static mem
0x559c58bcf154
0x559c58bcf154
0x559c58bcf154
0x559c58bcf154

值得注意的是,静态成员的访问方式,上例使用了4种方式来访问:

  • 通过基类
  • 通过派生类
  • 通过派生类参数对象
  • 通过派生类的this指针

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值