c++学习--静态成员的继承规则

using namespace std;

class father{
public:
  //  static int static_inter = -1;                                                                                                                       
  static int static_inter;
public:
  static int get_static_inter(){
    return static_inter;
  }

  static void set_static_inter(int i){
    static_inter = i;
  }

  void print(){
    cout << "Father print " << endl;
  }
};

class child:public father{
public:
  static int static_inter;
  void print(){
    cout << "Child print " << endl;
  }

  static void set_static_inter(int i){
    static_inter = i;
  }

};

int father::static_inter = 50;
int child::static_inter = 100;

int main(int argc, char *argv[])
{
  child ch;

  father::set_static_inter(5);
  child::set_static_inter(101);

  cout << "fa static: " << father::get_static_inter() << endl;
  cout << "fa static inter: " << father::static_inter << endl;
  cout << "ch static: " <<  child::static_inter << endl;
  cout << "ch static: " <<  child::father::static_inter << endl;
}

执行结果:

fa static: 5
fa static inter: 5
ch static: 101
ch static: 5

 

总结:

1,静态成员必须类外显示初始化,不然会报错。

2,不论静态与非静态,对于子类和父类都有定义的情况,尊从重定义原则。--子类没有,用父类的,子类有,各用各的。不管子类有没有,都可以通过类名的方式调用父类的。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值