构造函数

1. 类中没有创建默认构造函数,但有带参数的构造函数

编译不通过,除非参数有默认参数值。

如:

class Base

{

public:

      Base( int i )

{

}

};

添加默认参数,例如:

 Base( int i  = 9 )

{

}

 

2.

(1)

class Base

{
public:
    Base()
    {
        cout<<"Base::Base()"<<endl;
    }
  };

 

class Drived: public Base

{
public:
    Drived()
    {
        cout<<"Drived::Drived()"<<endl;
    }
   };
当调用Drived d;时,会先调用Base(), 再调用Drived().
 
 
(2)

class Base

{
public:
        Base(int i = 9 )
    {
        cout<<"Base::Base("<<i<<")"<<endl;
    }

};

 

class Drived: public Base

{
public:
    Drived()
    {
        cout<<"Drived::Drived()"<<endl;
    }
    Drived(int i):Base(i)
    {
        cout<<"Drived::Base("<<i<<")"<<endl;
    }
};
当调用Drived d;时, 会先调用Base(9), 再调用Drived().

(3)

class Base

{
public:
Base( )
    {
        cout<<"Base::Base("<<i<<")"<<endl;
    }
        Base(int i  )
    {
        cout<<"Base::Base("<<i<<")"<<endl;
    }

};

 

class Drived: public Base

{
public:
    Drived()
    {
        cout<<"Drived::Drived()"<<endl;
    }
    Drived(int i):Base(i)
    {
        cout<<"Drived::Base("<<i<<")"<<endl;
    }
};
当调用Drived d(4);时, 会先调用Base(int i), 再调用Drived(int i).

你可能感兴趣的:(构造函数)