成员初始化列表

来源:互联网 发布:古装拍照软件 编辑:程序博客网 时间:2024/05/22 08:29

一.1.用const修饰的数据成员

        用引用类型的数据成员

        是不允许用赋值语句直接赋值的.因此,只能用成员初始化列表对其进行初始化。 

#include<iostream> using namespace std;class A{ public:  A(int x1):x(x1),rx(x),pi(3.14)  //使用成员初始化列表赋值  {  }  void print()  { cout<<"x="<<x<<"  "<<"rx="<<rx<<"        "<<"pi="<<pi<<endl;} private:  int x;  int& rx;        //引用      const double pi; }; //constint main(){ A a(10);  a.print();  return 0;} 


2.数据成员是按照它们在类中声明的顺序进行初始化的,与它们在成员初始化列表中列出的顺序无关。
#include<iostream>using namespace std;class D {   int mem1;  //类中声明的顺序   int mem2; public:   D(int i):mem2(i),mem1(mem2+1)    //成员初始化列表中列出的顺序   { cout<<"mem1: "<<mem1<<endl;     cout<<"mem2:"<<mem2<<endl; } };void main(){  D d(15); } 

程序结果如下:
   mem1: -858993459

   mem2: 15

二.常数据成员:

       使用const说明的数据成员称为常数据成员

       要求:1.常数据成员必须在类外进行初始化

                    2.构造函数只能通过成员初始化列表对该类数据成员初始化

#include<iostream>    using namespace std;class Date {  private:    const int year;     const int month;     const int day; public:   Date(int y,int m,int d);    void showDate();  };  Date::Date(int y,int m,int d) :year(y),month(m),day(d)  { }inline void Date::showDate(){  cout<<year<<"."<<month<<"."<<day<<endl;} int  main(){ Date date1(1998,4,28);        date1.showDate();  return 0; }


三.多继承中派生类的构造函数要使用成员初始化列表

#include<iostream.h>      class B {  int a;  public:   B(int sa)  { a=sa;  cout<<"Constructing B"<<endl; } };class B1:virtual public B{  int b;  public:   B1(int sa,int sb):B(sa)   { b=sb; cout<<"Constructing B1"<<endl; } };class B2:virtual public B{  int c;  public:   B2(int sa,int sc):B(sa)  { c=sc; cout<<"Constructing B2"<<endl; } };class D:public B1,public B2 {   int d;  public:   D(int sa,int sb,int sc,int sd): B(sa),B1(sa,sb),B2(sa,sc)   { d=sd; cout<<"Constructing D"<<endl;} }; main(){ D  obj(2,4,6,8); return 0; }


0 0
原创粉丝点击