c++0x11新特性:delete删除函数

c_plus_plus_0x11.cpp:

// c_plus_plus_0x11.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;

class A
{
public:
    int add(int a, int b){ return a + b; }
    int sub(int a, int b){ return a - b; }
};

class B :public A
{
public:
    //int sub(int a, int b) = delete;
};


int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    cout << "5+2=" << a.add(5, 2) << endl;
    cout << "5-2=" << a.sub(5, 2) << endl<<endl;

    B b;
    cout << "9+3=" << b.add(9, 3) << endl;
    cout << "9-3=" << b.sub(9, 3) << endl << endl;


    cout << "done" << endl;
    getchar();
    return 0;
}

运行效果:

 

把此行代码注析删除:

//int sub(int a, int b) = delete;

重新编译,结果为:

 

可见,delete可以用来删除一个类从基类继承的函数,听说可以用来删除拷贝构造函数,下面再尝试一下。

c_plus_plus_0x11.cpp:

// c_plus_plus_0x11.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;

class A
{
public:
    A(int a, int b){ a_ = a; b_ = b; }
    int add(){ return a_ + b_; }
    int sub(){ return a_ - b_; }

    //A(const A&) = delete;        // no copy

    int a_{};
    int b_{};
};

int _tmain(int argc, _TCHAR* argv[])
{
    A a(5,2);
    cout << "5+2=" << a.add() << endl;
    cout << "5-2=" << a.sub() << endl<<endl;

    A b=a;
    cout << b.a_ << "+" << b.b_ << "=" << b.add() << endl;
    cout << b.a_ << "-" << b.b_ << "=" << b.sub() << endl;


    cout << "done" << endl;
    getchar();
    return 0;
}

运行效果:

把此行代码注析删除:

    //A(const A&) = delete;        // no copy

重新编译:

 

估计delete可以用来删除一个类从基类继承(如A.sub函数)的和此类隐式存在(如拷贝构造函数)的函数。

 

资料来源:

C++11 FAQ  http://www.stroustrup.com/C++11FAQ.html#default

 

完。

转载于:https://www.cnblogs.com/liyou-blog/p/4596968.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值