C++笔记——构造函数和析构函数

构造函数

完成对象的初始化的函数是构造函数。

类的对象的初始化只能由类的成员函数来进行。

建立对象的同时,自动调用构造函数。

类对象的定义涉及到一个类型和一个对象名。

由于类的唯一性和对象的多样性,用类名而不是对象名来作为构造函数名是比较合适的。

每个类必须有一个构造函数,只要一个类定义了一个构造函数,就不再提供默认构造函数(默认具有随机性)。

与变量定义类似,在用默认构造函数创建对象时。如果创建的是全局对象或静态对象,则对象的位模式全为0,否则,对象值是随机的。

构造函数没有返回类型。可以有多个,可以重载,可以用于隐式类型转换。

main.cpp

#include <iostream>
#include "car.h"

using namespace::std;

int main()
{
    Car a;
    cout << "end of define Car a" << endl;
    a.print();
    a.setProperty(10000, 123456);
    a.print();
    a.run();
    return 0;
}
car.h

#ifndef CAR_H_INCLUDED
#define CAR_H_INCLUDED

class Car{
public:
    Car(int pric = 10000, int carNum = 0);   // 构造函数的声明
    void run();
    void stop();
    void setProperty(int price, int carNum);
    void print();
private:   // 数据成员私有
    int m_price;
    int m_carNum;
};

#endif // CAR_H_INCLUDED
car.cpp

#include <iostream>
#include "car.h"

using namespace::std;

Car::Car(int pric, int carNum)   // 构造函数的定义
{
    cout << "Car constructor" << endl;
    setProperty(pric, carNum);
}

void Car::run()
{
    cout << "Car run" << endl;
}
void Car::stop()
{
    cout << "Car stop" << endl;
}

void Car::setProperty(int price, int carNum)
{
    this -> m_price = price;   // this: 成员函数中,当前对象的指针
    this -> m_carNum = carNum;
}

void Car::print()
{
    cout << "This car price is " << m_price << endl;
    cout << "This car number is " << m_carNum << endl;
}


析构函数

一个类可能在构造函数里分配资源,这些资源需要在对象不复存在以前被释放。

析构函数没有返回类型,没有参数。不能随意调用,只有一个,不能重载。只是在类对象生命期结束的时候由系统自动调用。

析构函数名,就在构造函数名前加上一个逻辑非运算行“~”,表示“逆构造函数”。

如果类没有自定义析构函数,则编译器提供一个默认的析构函数。

main.cpp

#include <iostream>
#include "student.h"

using namespace::std;

void fun(Student stu)
{

}

int main(int argc, char *argv[])
{
    Student john(1001);
    cout << "return from main" << endl;
    /*
    fun(john);
    fun(1002);  // 隐式类型转换
    */
    return 0;
}
student.h

#ifndef STUDENT_H_INCLUDED
#define STUDENT_H_INCLUDED

class Student{
public:
    Student(int id = 0);
    ~Student();
    inline int getId()
    {
        return m_id;
    }
    void setId(int id)
    {
        m_id = id;
    }

    int getScore()
    {
        return m_score;
    }
    void setScore(int score)
    {
        m_score = score;
    }

private:
    int m_id;
    int m_score;

};


#endif // STUDENT_H_INCLUDED
student.cpp

#include <iostream>
#include "student.h"

using namespace::std;

Student::Student(int id)   // 构造函数的定义
    :m_id(id), m_score(0)  // 冒号表示后面要对类的数据成员进行初始化
{
    cout << "Student constructor" << endl;
}

Student::~Student()
{
    cout << "Student destructor" << endl;
}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值