C++之类的六个默认成员函数

在C++类中同样的默认成员函数一共有六个,即使用户不定义,编译器也可以给出。分别为:
1、构造函数;
2、析构函数;
3、拷贝构造函数;
4、赋值运算;
5、取地址运算;
6、const取地址运算;

我们一下述程序为例验证下上面说法:

#include <iostream>
using namespace std;

class complex
{
public:
    complex()                      //构造函数
    {
        cout << "complex()!!\n";
    }
    ~complex()                     //析构函数
    {
        cout << "~complex()!!" << endl;
    }
    complex(const complex &c)      //拷贝构造函数
    {
        m_real = c.m_real;
        m_image = c.m_image;

        cout << "complex(const comple &c)!!" << endl;
    }
    complex& operator=(const complex &c)                 //赋值运算
    {
        if(this != &c){
            m_real = c.m_real;
            m_image = c.m_image;
        }
        cout << "complex operator=(const complex &c)!!" << endl;

        return *this;
    }
    complex* operator&(const complex &x)             //取地址运算
    {
        cout << "complex& operator=(const complex &x)!!" << endl;

        return this;
    }
    const complex* operator=(const complex &c)const    //const取地址运算
    {
        cout << "const complex& operator=(const complex &c)const!!" << endl;

        return this;
    }
private:
    int m_real;
    int m_image;
};

int main()
{
    complex c1;                //构造函数
    complex c2 = c1;           //拷贝构造函数
    complex c3;                //构造函数
    c3 = c1;                   //赋值运算
    complex *pa = &c2;         //取地址运算
    const complex *pb = &c2;   //const取地址运算

    return 0;
}

*运行结果:*
这里写图片描述

我们可以看到每次都调用了相应的函数,下面我们看下如果不定义这些程序会不会成功运行吧!

#include <iostream>
using namespace std;

class complex
{
public:

private:
    int m_real;
    int m_image;
};

int main()
{
    complex c1;                //构造函数
    complex c2 = c1;           //拷贝构造函数
    complex c3;                //构造函数
    c3 = c1;                   //赋值运算
    complex *pa = &c2;         //取地址运算
    const complex *pb = &c2;   //const取地址运算

    return 0;
}

运行结果:
这里写图片描述

运行后我们发现程序完全ok,并没有错误,所以当我们没定义时,体贴的编译器也会帮我们提供这六种默认成员函数的。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值