explicit关键字

目录

修饰构造函数

修饰转换运算符


         主要用于修饰构造函数或者转换运算符,为了增强类型安全性和防止意外的类型转换,防止他们被编译器隐式地用于类型转换。

修饰构造函数

class MyString {
public:
    MyString(const char* str) { /*...*/ }
    // ...
};

void PrintString(const MyString& str) { /*...*/ }

int main() {
    PrintString("Hello, world!"); // 隐式转换 const char* 到 MyString
}

这段代码中,PrintString应该接收一个MyString类型得引用作为参数,但是在main中传递一个一个char* str类型给它,由于MyString有一个接受char* str类型得构造函数,编译器自动隐式使用这个构造函数创建一个MyString对象。防止这种转换可以使用explicit关键字:

class MyString {
public:
    explicit MyString(const char* str) { /*...*/ }
    // ...
};

这时再使用PrintString("Hello, world!");会报错。

修饰转换运算符

class MyClass {
public:
    operator bool() const { return true; } // 隐式转换到bool
};

MyClass obj;
if (obj) { /*...*/ } // obj隐式转换为bool

这里obj会被隐式转换成bool类型,使用explicit之后不会转换:

class AnotherClass {
public:
    explicit operator bool() const { return true; } // 明确要求转换到bool
};

AnotherClass anotherObj;
// if (anotherObj) {}  // 这将导致编译错误,因为explicit阻止了隐式转换
if (static_cast<bool>(anotherObj)) { /*...*/ } // 这是正确的

这时这里得anotherObj还是原来得类型,如果想使用得化需要自己转换成bool类型。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值