在早期的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了!