C++关键字之explicit

1.定义

explicit 是 C++ 中的一个关键字,用来修饰 构造函数类型转换运算符,避免它们在不明确的情况下被隐式调用,从而提升代码的可读性和安全性。

2.用于构造函数

默认情况下,单参数构造函数允许隐式类型转换。例如:

#include <iostream>
class Example {
public:
	Example(int x) {//单参数构造函数
		cout << "Constructor called with:" << x << endl;
	}
};
int main() {
	Example obj = 42;//隐式调用构造函数
	return 0;
}

输出:Constructor called with: 42

这里,Example obj = 42; 隐式地调用了构造函数,将 int 类型转换为 Example 类型。

避免隐式转换

为避免这种隐式转换,可以在构造函数前加上 explicit 关键字:

#include<iostream>

class Example {
public:
	explicit Example(int x) {
		cout << "Constructor called with:" << x << endl;
	}
};
int main() {
	//Example obj = 42;不存在从int转换到Example的适当构造函数
	Example obj2(42);
	return 0;
}

3. 用于类型转换运算符

当定义类型转换运算符时,默认情况下允许隐式转换。例如:

#include <iostream>

class Example {
public:
    operator int() const {  // 类型转换运算符
        return 42;
    }
};

int main() {
    Example obj;
    int x = obj;  // 隐式调用类型转换运算符
    std::cout << x << std::endl;  // 输出 42
    return 0;
}

避免隐式转换

可以通过 explicit 禁止隐式调用类型转换运算符:

#include <iostream>

class Example {
public:
    explicit operator int() const {  // 显式类型转换
        return 42;
    }
};

int main() {
    Example obj;
    // int x = obj;  // 错误,隐式转换被禁止
    int y = static_cast<int>(obj);  // 正确,显式转换
    std::cout << y << std::endl;  // 输出 42
    return 0;
}

4.C++11的改进

在 C++11 及之后,explicit 可以用于 带多个参数 的构造函数(配合参数的默认值)。

#include <iostream>

class Example {
public:
    explicit Example(int x, int y = 0) {
        std::cout << "Constructor called with: " << x << " and " << y << std::endl;
    }
};

int main() {
    Example obj1(10);         // 正确,显式调用
    Example obj2 = {10, 20};  // 错误,禁止隐式调用
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值