zoukankan      html  css  js  c++  java
  • 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

    完。

  • 相关阅读:
    [Scala] akka actor编程(一)
    随便说说
    [Java] Java执行Shell命令
    [Scala] Scala基础知识
    [Linux] 账户管理命令(二)
    [Linux] 账户管理命令(一)
    [Kerberos] Java client访问kerberos-secured cluster
    沟通与影响技术培训
    Python
    ML 基础知识
  • 原文地址:https://www.cnblogs.com/liyou-blog/p/4596968.html
Copyright © 2011-2022 走看看