C++基本知识整理(2)

来源:互联网 发布:荣誉证书在线制作软件 编辑:程序博客网 时间:2024/06/09 21:14

1、构造函数
C++中定义了一种特殊的初始化函数,称为构造函数;当对象被调用时,构造函数自动调用;构造函数名字与类名相同,也没有返回类型和返回值;对象在生成过程中通常需要初始化变量分配动态内存,用构造函数。
程序中可以没有构造函数,这时会执行一个空的构造函数。
下面来看构造函数实例:

#include <iostream>using namespace std;class Stu{private:    const char *m_name;    int m_age;    float m_score;public:    Stu();     /*定义一个空的构造函数*/    Stu(const char *name, int age, float score);    void show();};Stu::Stu()   /*这个构造函数只是将变量初始化,并没有进行其他操作*/{    m_name = NULL;    m_age = 0;    m_score = 0;}                            /*构造函数参数列表*/Stu::Stu(const char *name, int age, float score):m_name(name), m_age(age), m_score(score){}void Stu::show(){    cout <<m_name<<","<<m_age<<","<<m_score<<endl;  }int main(){    Stu stu("li", 12, 90.9);    stu.show();    Stu stu1();    stu1.show();    Stu *pstu = new Stu("jk", 11, 80);    pstu->show();    delete pstu;    return 0;}

2、析构函数
析构函数,是在对象被删除前由系统自动执行它作清理工作。
下面来看析构函数实例:

#include <iostream>using namespace std;class Carea{       /*定义一个类求长方形面积*/private:    int *length;    int *width;public:    ~Carea();        /*析构函数*/    Carea(int, int); /*构造函数*/    int area();};Carea::Carea(int a, int b)   /*构造函数中对变量初始化及为指针变量分配空间*/{    length = new int;    width = new int;    *length = a;    *width = b;    cout <<"start "<<endl;}Carea::~Carea()            /*析构函数中释放堆上为指针变量分配的内存*/{    delete length;    delete width;    cout <<"set free memory"<<endl; }int Carea::area(){    return ((*length) * (*width));}int main(){    Carea ca1(4, 6);    Carea ca2(6, 6);    cout <<"rect1: "<<ca1.area()<<endl;    cout <<"rect2: "<<ca2.area()<<endl;    return 0;}

这里写图片描述
再来看下一例:

#include <iostream>using namespace std;class Test{private:    int num;public:    Test(int);    ~Test();};Test::Test(int a){    num = a;    cout <<"第"<<num<<"次"<<"test"<<endl; }Test::~Test(){    cout <<"第"<<num<<"次"<<"~test"<<endl;   }int main(){    cout <<"main"<<endl;    Test a[4] = {0, 1, 2, 3};    cout <<"main is running"<<endl;    return 0;}

这里写图片描述
从结果中可以看出,构造函数的执行是按顺序执行的,而析构函数顺序刚好相反,析构函数总是在最后被调用,完成清理工作。

原创粉丝点击