c++笔记——explicit关键字

发布时间 2023-04-14 21:37:52作者: 水水滴答

前言:

explicit是为了自定义类在初始化或赋值时,发生数据类型隐性强制转换为类类型。

特点:

1、只对单实参的构造函数有效

2、只能在类内声明构造函数是用explict,在类外定义时不写explicit

3、explicit的构造函数在生成对象时,只能用直接初始化,不能赋值

示例1:

class Test{
public:
    //explicit Test(int a);
    Test(int a);
    Test(string str);
    ~Test()= default;

    int size_;
    string str_;

};

/*  //explicit在类外定义构造函数时,会报错
explicit Test::Test(int a){
    cout << "hello, this is testing..." << endl;
    size_ = a;
}
*/

Test::Test(int a){
    size_ = a;
    cout << "now test size." << endl;
}

Test::Test(string str) {
    str_ = str;
    cout << "now test str." << endl;
}


int main(){
    Test t0(12);//直接初始化
    Test t1 = 10;//赋值,实际上进行了隐式转换,将int型转换为Test类型
    Test t2('c');//调用的是int 字符c对应的assic码
    Test t3("jelly");//调用的是string

    return 0;
}

示例2:加上explicit

#include<iostream>
#include<vector>
#include <string>
using namespace std;


class Test{
public:
explicit Test(int a);
//Test(int a);
Test(string str);
~Test()= default;

int size_;
string str_;

};

/* //explicit在类外定义构造函数时,会报错
explicit Test::Test(int a){
cout << "hello, this is testing..." << endl;
size_ = a;
}
*/

Test::Test(int a){
size_ = a;
cout << "now test size. and size_ = " << size_ << endl;
}

Test::Test(string str) {
str_ = str;
cout << "now test str." << endl;
}


int main(){
Test t0(12);
Test t12(2.3);
//Test t1 = 10;
Test t2('c');
Test t3("jelly");

return 0;
}

  这里t1报错,不能直接赋值,会发生类型转换

另外,关注到t12,t2这两个初始化操作,仍然发生了内置类型的隐式转换(float转换为int, char转换为int),即使有explicit,结果如下。

  

说明explicit只对自定义类型的强制转换有限制。