• C++学习笔记16,C++11中的显式的默认构造函数以及显示删除默认构造函数


    在早期的C++中。假设须要一些接受一些參数的构造函数,同一时候须要一个不接收不论什么參数的默认构造函数。就必须显示地编写空的默认构造函数.比如:

    //tc.h
    class A{
    private:
    	int i;
    public:
    	A(){};
    	A(int ii);
    };
    但最好就是接口和声明分离。那么就是例如以下的定义

    //tc,h
    class A{
    private:
    	int i;
    public:
    	A();
    	A(int ii)。
    };
    这样,就必须在实现中给出空參数构造函数的实现:

    #include <iostream>
    #include "tc.h"
    using namespace std;
    A::A(){//必须给出事实上现
    	};
    A::A(int ii){
    		i=ii;
    	}
    void A::show()const{
    		std::cout<<"this is A object!"<<std::endl;
    	};
    int main()
    {
    	A a;
    	a.show();
    }
    
    为了避免手动编写空默认构造函数,C++11引入了显示默认构造函数的概念,从而仅仅需在类的定义中编写空默认构造函数而不须要在实现文件里提供事实上现:

    //tc.h
    #ifndef tc_h_
    #define tc_h_
    class A{
    private:
    	int i;
    public:
    	A()=default;//default
    	A(int ii);
    	void show()const;
    };
    #endif
    
    //tc.cpp
    #include <iostream>
    #include "tc.h"
    using namespace std;
    /*
    A::A(){//不必给出事实上现
    	};
    */
    A::A(int ii){
    		i=ii;
    	}
    void A::show()const{
    		std::cout<<"this is A object!"<<std::endl;
    	};
    int main()
    {
    	A a;
    	a.show();
    }
    
    编译以及运行结果:


    相同的,C++还支持显式删除构造函数的概念。

    比如。你想定义一个类。这个类没有不论什么的构造函数,而且你也不想让编译器自己主动生成一个默认的空參数的构造函数,那么你就能够显式地删除默认构造函数。

    //tc.h
    #ifndef tc_h_
    #define tc_h_
    class A{
    private:
    	int i;
    public:
    	A()=delete;//delete
    	void show()const;
    };
    #endif
    
    //tc.cpp
    #include <iostream>
    #include "tc.h"
    using namespace std;
    /*
    A::A(){//必须给出事实上现
    	};
    
    A::A(int ii){
    		i=ii;
    	}*/
    void A::show()const{
    		std::cout<<"this is A object!"<<std::endl;
    	};
    int main()
    {
    	A a;
    	a.show();
    }
    

    编译结果:


    能够看到,默认构造函数被删除了。那么。能不能删除一些其它的带參数构造函数呢?

    事实上这个问题有点多余,由于假设你不想要这个构造函数,你不定义这个带參的构造函数就OK了!








  • 相关阅读:
    EF 学习代码
    VS10 调试 新功能
    高级编程 实验代码
    事务 代码
    ADO.NET的新功能:MARS(Multiple Active Result Set) 及 异步执行命令
    Log4Net
    获得CheckBoxList最后一个被操作的项
    在存储过程中用事务
    ASP.NET服务端添加客户端事件
    GridView遍历各行的控件和控件事件
  • 原文地址:https://www.cnblogs.com/slgkaifa/p/6728424.html
Copyright © 2020-2023  润新知