1.隐式类型转换
C++中定义了内置类型的几个自动转换,为了定义到类类型的隐式转换,必须定义合适的构造函数。
可以用单个实参来调用的构造函数定义了从形参类型到该类类型的隐式转换。
来看一下例子:
#include <iostream>
#include <stdio.h>
using namespace std;
#include <iostream>
using namespace std;
class Base
{
private:
int data;
public:
Base(){ cout << "defalut constructor \n" << endl;}
// this is a destructor:
~Base(){ cout<<"destructed" << endl;}
Base(int i):data(i)
{
cout << "constructed by parameter " << data << endl;
}
};
Base play( Base b)
{
return b;
}
int main()
{
Base temp = play(5);
return 0;
}
打印输出一下:
可以看到在需要一个Base类型的参数,传入 int类型,会自动调用 隐式转换。生成一个 Base对象,该对象 在局部函数完毕后就 自动析构,如果想抑制这种隐式转换,需要在前面加一个explicit 参数。
explicit关键字 只能用在类内部的构造函数声明中,不能加在定义的前面。
总结:单个参数的构造函数不添加explicit参数的时候,会定义一个从隐式转换,从参数的类型到自己的类类型。添加explicit就会消除这种隐患。
添加了之后可以显式的使用构造函数来构造。下面这样。
#include <iostream>
#include <stdio.h>
using namespace std;
#include <iostream>
using namespace std;
class Base
{
private:
int data;
public:
Base(){ cout << "defalut constructor \n" << endl;}
// this is a destructor:
~Base(){ cout<<"destructed" << endl;}
explicit Base(int i):data(i)
{
cout << "constructed by parameter " << data << endl;
}
};
Base play( Base b)
{
return b;
}
int main()
{
Base temp = play(Base(5));
return 0;
}
2.构造函数默认实参
默认实参的作用是减少代码重复。看下面的构造函数
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
class MyString
{
private:
char *m_data;
public:
//普通构造函数
MyString(const char * str = NULL);
}
MyString::MyString(const char *str)
{
cout << "constructing string by " << str << endl;
if(str == NULL)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
int len = strlen(str);
m_data = new char[len + 1];
strcpy(m_data,str);
}
}
int main()
{
MyString s;
}
加上一个默认实参,可以 直接 定义 没有参数的 s
,默认实参只能出现在 声明中,不能出现在定义中。如
MyString::MyString(const char *str = NULL)
就是错误的。