文章目录
1 C++中的转换构造函数
1.1 转换构造函数
我们知道构造函数可以定义不同类型的参数,参数满足下列条件时称为转换构造函数:
- 有且仅有一个参数。
- 参数是基本类型。
- 参数是其它类类型。
看如下代码:
编译器尽力尝试的结果是隐式类型转换,隐式类型转换:
- 会让程序以意想不到的方式进行工作。
- 是工程中bug的重要来源。
1.2 explicit关键字
explicit关键字:
- 工程中通过explicit关键字杜绝编译器的转换尝试。
- 转换构造函数被explicit修饰时只能进行显示转换。
普通类型到类类型示例代码:
#include <iostream>
#include <string>
using namespace std;
class Test
{
int mValue;
public:
Test()
{
mValue = 0;
}
explicit Test(int i)
{
mValue = i;
}
Test operator + (const Test& p)
{
Test ret(mValue + p.mValue);
return ret;
}
int value()
{
return mValue;
}
};
int main()
{
Test t;
t = static_cast<Test>(5); // t = Test(5);
Test r;
r = t + static_cast<Test>(10); // r = t + Test(10);
cout << r.value() << endl;
return 0;
}
2 C++中的类型转换函数
2.1 类型转换函数
为了实现类类型到普通类型之间的转换,我们需要引入类型转换函数。
类型转换函数:
- C++类中可以定义类型转换函数。
- 类型转换函数用于将类对象转换为其他类型。
类型转换函数:
- 与转换构造函数具有同等的地位。
- 使得编译器有能力将对象转换为其他类型。
- 编译器能够隐式的使用类型转换函数。
类类型到普通类型之间的转换:
#include <iostream>
#include <string>
using namespace std;
class Test
{
int mValue;
public:
Test(int i = 0)
{
mValue = i;
}
int value()
{
return mValue;
}
operator int ()
{
return mValue;
}
};
int main()
{
Test t(100);
int i = t;
cout << "t.value() = " << t.value() << endl;
cout << "i = " << i << endl;
return 0;
}
3 转换构造函数与类型转换函数之间的冲突
3.1 转换构造函数与类型转换函数之间的冲突
#include <iostream>
#include <string>
using namespace std;
class Test;
class Value
{
public:
Value()
{
}
explicit Value(Test& t)
{
}
};
class Test
{
int mValue;
public:
Test(int i = 0)
{
mValue = i;
}
int value()
{
return mValue;
}
operator Value()
{
Value ret;
cout << "operator Value()" << endl;
return ret;
}
};
int main()
{
Test t(100);
Value v = t; // 编译error,转换构造函数和类型转换函数都可以完成,编译器不知道选择哪一个函数,我们可以将转换构造函数前加上explicit关键字
return 0;
}
3.2 解决方案
转换构造函数与类型转换函数:
- 无法抑制隐式的类型转换函数调用。
- 类型转换函数可能与转换构造函数冲突。
- 工程中以Type toType()的公有成员代替类型转换函数。
qt中的解决方案:
#include <QDebug>
#include <QString>
int main()
{
QString str = "";
int i = 0;
double d = 0;
short s = 0;
str = "-255";
i = str.toInt();
d = str.toDouble();
s = str.toShort();
qDebug() << "i = " << i << endl;
qDebug() << "d = " << d << endl;
qDebug() << "s = " << s << endl;
return 0;
}
参考资料: