我正在阅读 Bjarne Stroustrup 的“The C++ Programming Language”来学习 C++,并遇到以下段落:
The
static_cast
operator converts between related types such as one pointer type to another in the same class hierarchy, an integral type to an enumeration, or a floating-point type to an integral type. Thereinterpret_case
handles conversions between unrelated types such as an integer to a pointer or a pointer to an unrelated pointer type.
对我来说,不清楚是什么决定了任何两个给定类型是相关的还是不相关的,所提到的例子似乎并不详尽。
Stroustrup 说类型分为 1. 算术类型 2. 用户定义类型和 3. 内置类型,从上面的例子中,他认为算术类型 (int) 与用户定义类型有关(枚举)。 float 类型到 int 是显而易见的,因为它们都是算术类型。
但是,他将两个按他的定义应该都是内置类型的指针归类为无关。
那么我们所说的“两种类型相关(不相关)”到底是什么意思呢?
最佳答案
在下面的示例中,类型 A 和 B 是相关的,而类型 A 和 C 以及类型 B 和 C 是不相关的:
class A
{
...
};
class B : public A
{
...
};
class C
{
...
};
一般来说,我认为类型 X 和 Y 相关当且仅当满足以下条件之一:
- X继承自Y
- Y继承自X
- X 有一个通过引用获取 Y 对象的构造函数,意思是 X::X(Y& y)
- Y 有一个构造函数,它通过引用获取 X 对象,意思是,Y::Y(X& x)
- X 有一个转换为 Y 的运算符,意思是 X::operator Y()
- Y 有一个到 X 的转换运算符,意思是,Y::operator X()
关于c++ - C++ 中的类型转换 : related and unrelated types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20930858/