c++类中的六种默认函数

来源:互联网 发布:美妆凯文老师的淘宝店 编辑:程序博客网 时间:2024/06/05 19:33
    今天和大家要说的就是c++类中的六大默认函数,这些函数的调用是不由用户给出的,系统自动完成调用,这六种分别是:

        <1> 构造函数

        <2>拷贝函数

        <3>赋值运算

        <4>非const的取址运算

        <5>const的取址运算

        <6>析构函数

    下面给出简单的代码进行验证:

 

#include <iostream>using namespace std;class Test{public:    //构造函数    Test(int x = 0):data(x)    {        cout<<"creat object!!"<<endl;    }    //拷贝构造    Test(const Test &s)    {        data = s.data;        cout<<"copy creat"<<endl;    }    //赋值    Test& operator=(const Test& t)    {        data = t.data;        cout<<"operator=!!"<<endl;    }    //取址运算赋(非const)    Test* operator&()    {         return this;         cout<<"operator&!!"<<endl;    }    //取址运算符(const)    const Test* operator&()const    {         return this;         cout<<"const operator&!!"<<endl;    }    //析构函数    ~Test()    {        cout<<"destory object!!"<<endl;    }private:    int data;};int main(int argc,char **argv){    Test t1;             //构造函数    Test t2(10);         //构造函数    Test t3 = t2;        //拷贝构造函数    Test t4;             //构造函数    t4 = t2;             //赋值函数    const Test t5(10);   //构造函数    Test *pt = &t2;      //非const的取址运算符    const Test *p = &t5; //const的取址运算符    return 0;}
 下面给出执行的结果:

       

  其中析构函数的调用严格与构造相反!!!

0 0
原创粉丝点击