C++ 同时定义显式类型转换和隐式类型转换
问题描述:
我声明并定义了这样的一个类:
- class A {
- public:
- operator bool();
- explicit operator bool();
- };
- A::operator bool() {
- return true;
- };
- explicit A::operator bool() {
- return false;
- };
复制代码在编译代码的时候,出现了这样的错误:'explicit' outside class declaration
redefinition of 'A::operator bool()'
但是,我删除 explicit 会导致两个函数的定义名字一样,怎么办?
我希望实现这样的效果:
- A test;
- (bool)test; // false
- bool result = test; // true
复制代码
回答:
在 C++ 中,只能同时定义一个类型转换函数为显式转换(explicit)或者隐式转换(implicit),不能同时定义为两种转换方式。
根据你的需求,你可以将其中一个转换函数定义为显式转换,另一个转换函数使用默认的隐式转换。请参考以下代码:
- class A {
- public:
- explicit operator bool(); // 显式转换
- operator bool() const; // 隐式转换
- };
- A::operator bool() {
- return true;
- }
- A::operator bool() const {
- return false;
- }
复制代码
通过上述修改,你可以实现以下效果:
- A test;
- (bool)test; // 使用显式转换,返回 false
- bool result = test; // 使用隐式转换,返回 true
复制代码
请注意:
1. 在定义显式转换函数时,不需要在类外部再次使用
explicit 关键字进行标记。
2. 为了区分两个转换函数,我在第二个转换函数中添加了
const 修饰符,表示该函数不会修改对象的状态。
希望上述回答对你有帮助。如果你有任何其他问题,请随时提问。
球一个最佳答案谢谢啦!这对我非常重要!
