欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

5.构造函数

程序员文章站 2022-06-26 12:53:22
...

1.构造函数就是对象的初始化

class complex{
    private:
        double real,imag;
    public:
        complex(double r,doublei=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.一个类可以有多个构造函数,参数个数或者类型不同。

complex::complex(double r)
{
    real=r;imag=0;
}
complex::complex(complex c1,complex c2)
{
    real=c1.real+c2.real;
    imag=c1.imag+c2.imag;
}
complex c1(3),c2(1,0),c3(c1,c2);
//c1={3,0},c2={1,0},c3={4,0};

3.构造函数初始化重载的例子

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

4.构造函数在数组中的使用

class test{
    public:
        test(int n){} //1
        test(int n,int m)  //2
        test(){}  //3
};
test array[3]={1,test(1,2)};  //三个元素分别用1,2,3初始化
test array[3]={test(2,3),test(1,2),1}; //三个元素分别用2,2,1初始化
test *parray[3]={new test(4),new test(1,2)};
相关标签: c++ c++