在早期的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
#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
#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
#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了!
—————————————————————————————————————————————————— //写的错误或者不好的地方请多多指导,可以在下面留言或者给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。 转载请注明出处:https://www.royalchen.com/ author:royalchen Email:royalchen@royalchen.com ———————————————————————————————————————————————————
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/c学习笔记16,c11中的显式的默认构造函数以及显示删/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!