OOP 2.2 构造函数

1、概念

  • 成员函数的一种
  • 名字与类名相同,可以有参数,没有返回值(void也不行)
  • 作用:对对象进行初始化,如给成员函数赋初始值
  • 如果定义时没有构造函数,则编译器生成一个默认无参数的构造函数
    • 默认构造函数无参数,不进行任何操作
  • 构造函数是在对象已经占用存储空间后,对对象进行一些初始化工作
  • 对象生成时构造函数自动被调用。对象一旦生成,就再也不能在其上执行构造函数
  • 一个类可以有多个构造函数
  • 构造函数的意义:构造函数执行必要的初始化工作,有了构造函数就不必专门写初始化函数,也不用担心忘记调用初始化函数
    e.g.
class complex{
    pravate:
        double real,imag;
    public:
        viod set(double r,double i);
};//编译器自动生成默认构造函数
complex c1;//默认构造函数被调用
complex *pc=new complex;//默认构造函数被调用

e.g.

class complex{
    private:
        double real,imag;
    public:
        complex(double r,double i=0);
};
complex::complex(double r,double i){
    real=r;imag=i;
}
complex c1;//error 缺少构造函数的参数
complex *pc=new complex;//error 缺少参数
complex c1(2);//OK
complex c1(2,4),c2(3,5);//OK
complex *pc=new complex(3,4);//OK
  • 可以有多个构造函数(重载),参数个数或类型不同

2、构造函数在数组中的使用

class cs{
    int x;
    public:
    cs(){
        cout<<"1 called"<<endl;
    }
    cs(int n){
        x=n;
        cout<<"2 called"<<endl;
    }
};
int main()
{
    cs array1[2];
    cout<<"step1"<<endl;
    cs array2[2]={4,5};
    cout<<"step2"<<endl;
    cs array3[2]={3};
    cs *array4=new cs[2];
    delete []array4;
    return 0;
}
/*
output:
1 called
1 called
step 1
2 called
2 called
step 2
2 called
1 called
step3
1 called
1 called
*/

e.g.



原文地址:https://www.cnblogs.com/fzu-031702148/p/8456843.html