explicit关键字——防止构造函数隐式转换

参见:【028】深入理解C++ 类和对象:构造、析构、拷贝构造、初始化列表 详解(最全讲解)_c++类构造初始化-CSDN博客

C++提供了关键字explicit 禁止通过构造函数进行的隐式转换;声明为explicit的构造函数不能在隐式转换中使用。

explicit用于修饰构造函数构造函数,防止隐式转换;是针对单参数的构造函数(或者除了第一个参数外其余参数都有默认值的多参数构造)而言的。

一、不使用 explicit 的情况(允许隐式转换)

#include <iostream>

class Example {
public:
    // 单参数构造函数(未使用 explicit)
    Example(int x) {
        value = x;
        std::cout << "Constructor called with value: " << value << std::endl;
    }

    int getValue() const {
        return value;
    }

private:
    int value;
};

void displayExample(const Example &ex) {
    std::cout << "Value is: " << ex.getValue() << std::endl;
}

int main() {
    Example ex1 = 100; // 隐式转换,调用 Example(int x) 构造函数
    displayExample(200); // 隐式转换,调用 Example(int x) 构造函数

    return 0;
}
Constructor called with value: 100
Constructor called with value: 200
Value is: 200

二、使用 explicit 的情况(禁止隐式转换)

#include <iostream>

class Example {
public:
    // 单参数构造函数(使用 explicit)
    explicit Example(int x) {
        value = x;
        std::cout << "Constructor called with value: " << value << std::endl;
    }

    int getValue() const {
        return value;
    }

private:
    int value;
};

void displayExample(const Example &ex) {
    std::cout << "Value is: " << ex.getValue() << std::endl;
}

int main() {
    Example ex1(100); // 直接调用构造函数,可以成功
    displayExample(ex1); // 直接传递对象,可以成功

    // Example ex2 = 200; // 错误! 隐式转换被禁止
    // displayExample(300); // 错误! 隐式转换被禁止

    return 0;
}
Constructor called with value: 100
Value is: 100

三、解释

  1. 不使用 explicit 的例子

    • 单参数构造函数 Example(int x) 可以被隐式调用。
    • 在 main 中 Example ex1 = 100; 和 displayExample(200); 都是隐式的,将 int 自动转换为 Example 对象。
  2. 使用 explicit 的例子

    • 在定义构造函数时使用 explicit 关键字:
      explicit Example(int x) { ... }
      
    • 在 main 中,必须使用直接的方式来调用构造函数和传递参数,不允许隐式转换。例如:
      Example ex1(100); // 显式调用
      displayExample(ex1); // 直接传递对象
      
    • 注释掉的代码会导致编译错误,因为 explicit 构造函数禁止隐式转换:
      Example ex2 = 200; // 错误! 隐式转换被禁止
      displayExample(300); // 错误! 隐式转换被禁止
      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值