C++显式构造函数

如果C++类的其中一个构造函数有一个参数,那么在编译的时候就会有一个缺省的转换操作:将该构造函数对应数据类型的数据转换为该类对象。

如下面的例子:

#include <iostream>
using namespace std;
class B{
public:
    int data;
    B(int _data):data(_data){}
    //explicit B(int _data):data(_data){}
};

int main(){
    B temp = 5;
    cout << temp.data << endl;
    return 0;
}

在程序的第11行:B temp = 5,因为B中存在一个只有一个参数的构造函数,且参数类型也是int,所以会将将int类型的5转换为B类型的对象,就是使用了隐式构造函数。

从上面例子来看,这样并没有什么坏处,反而使用起来比较方便,但是有的时候可能并不需要这种隐式转换,比如下面的例子:

class B
{
public:
    B(int iLength){}  //本意是预先分配n个字节给字符串
    B(const char *pString){}  // 用C风格的字符串p作为初始化值
};

int main(){
    B temp1 = B(5);
    B temp2 = B("a");
    B temp3 = 5; // 等价于B temp1 = B(5);
    B temp4 = "a"; // 等价于 B temp2 = B("a");
    B temp5 = 'a'; // 等价于 B temp2 = 97;

    return 0;
}

上述的写法中:

  • 前两种B temp1 = B(5); B temp2 = B("a"); 比较正常
  • B temp3 = 5;  B temp4 = "a"; 发生了隐式转换
  • 最后一个B temp5 = 'a'; 则等价于 B temp2 = 97; 是因为'a'属于字符,并不能和char*匹配,字母a的ASCII码值为97,在C和C++中,字符是以ASCII值存储的,所以会和参数为int型的构造函数进行匹配,分配int(‘a’)个字节的空字符串。而这种情况可能并不是我们想看到的(本意应该是希望将字符串初始化为"a")

为了避免这种错误的发生,我们可以声明显示的转换,使用explicit 关键字:

class B{
public:
    int data;
    explicit B(int _data):data(_data){}
};
class B
{
public:
    explicit B(int iLength){}
    B(const char *pString){}
};

则类似于B temp = 5这种写法编译不能通过,需要写 B temp(5)或者 B temp = B(5)。

参考:https://www.cnblogs.com/xudong-bupt/p/3671972.html   https://blog.csdn.net/smilelance/article/details/1528737

猜你喜欢

转载自blog.csdn.net/qq_36132127/article/details/81169986