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


猜你喜欢

转载自blog.csdn.net/u010029439/article/details/80668780
今日推荐