c++ - C++ 中的类型转换 : related and unrelated types

标签 c++

我正在阅读 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. The reinterpret_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/

相关文章:

c++ - 无法从 stringw 转换为 string/char

c++ - 为什么 std::condition_variable 不能正常工作?总是在等待之前通知

c++ - 我可以使用什么库在 C++ 中发送 POST 和 GET 请求?

c++ - 枚举注册表项 C++

c++ - 当基类是模板时,访问基类时的不同行为

c++ - 如何检查一个类是否具有特定功能以避免编译时问题?

c++ - 没有额外的实例方法和变量的对象切片

python - 如何在 TensorFlow 中实现递归神经网络?

c++ - 简单程序引用错误

c++ - 使用 mingw 在每个新库或可执行文件中重新初始化本地静态对象