栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

构造函数学习

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

构造函数学习

一.构造函数种类

        1.默认构造函数

        2.自定义构造函数

        3.拷贝构造函数

        4.赋值构造函数         

1.默认构造函数

        没有手动定义默认构造参数时,编译器为这个类定义一个构造函数(合成的默认构造函数)

(1)如果数据成员使用了“类内初始值”(C++11支持),就使用这个值来初始化数据成员

class Human{
    private :
        void getAge();
    
    public:
        int age=18;
        int name="张三"   //C++11支持
}

(2)否则,就使用默认初始化

【仅当数据成员全部使用了“类内初始值”,才适宜用“合成默认构造函数】

当定义了构造函数,编译器将不提供默认构造函数

2.自定义构造函数

        1)自定义构造函数

        2)自定义带参数构造函数

Human();

Human(int age,int salre);

如果某数据成员使用类内初始化值,同时又在构造函数中进行了初始化,那么以构造函数中的初始化为准。相当于构造函数中的初始化会覆盖对应的类内初始值。

3.拷贝构造函数

class Human{
    public:
        Human( int age, int salre){
                this->age=age;
                this->salre=salre;      
        }

    private:
        int age;
        int salre;
}

Human h1(18,28000);
Human h2 = h1;              //调用拷贝构造函数,编译器提供浅拷贝构造函数

        或者

class Human{
    public:
        Human( int age, int salre){
                this->age=age;
                this->salre=salre;      
        }
        
        Human(const Human & other);   //other可以不写

    private:
        int age;
        int salre;
}

Human::Human(const Human&other){
        this->age=other.age;
        this->salre=other.salre;
        
}

Human h1(18,28000);
Human h2 (h1);              //调用拷贝构造函数  自定义的浅拷贝构造函数

拷贝构造函数其他调用时机

1.调用函数时,实参是对象,形参不是引用类型

void showHuamn(Human man){

}

Hunman h1(18,28000);
showHuman(h1);

2.函数返回类型是类,而不是引用类型

Human showHuman(int a){

}

3.对象数组的初始化列表中,使用对象

Human f1,f2,f3,f4;           //f1、f2、f3、f已初始化
Human F4[4]={f1,f2,f3,f4};   //调用拷贝构造函数

4.赋值构造函数    

Human f1,f2;

f2=f1;     //自动调用赋值构造函数     如果写成Human f2 = f1;会调用拷贝构造函数
           //编译器提供的赋值构造函数也是浅拷贝(位拷贝)

//自定义赋值构造函数
public:
    Human &operator=(const Human &other){   //运算符重载
    

    }

//这时候使用f2 = f1 ;就相当于 f1.operator=(f2);

Human & Human ::operator=(coonst(Human&other){
    //防止对象给自己赋值 f1=f1;
    if(this==other){
        return *this;
    }

    name = other.name;
    age = other.age;

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/333176.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号