gpt4 book ai didi

c++ - C风格的类型转换和动态转换理解困难

转载 作者:太空狗 更新时间:2023-10-29 20:36:10 24 4
gpt4 key购买 nike

我一直在努力理解 C++ 中的类型转换。在下面的代码中,类 B 是类 A 的子类,两者共享多态关系。

#include <iostream>
using namespace std;
class A{
int a;
public:
virtual void sayhello() {cout<<"Hello from A"<<endl;}
};
class B:public A{
int b;
public:
void sayhello(){cout<<"Hello from B"<<endl;}
void another_func(){cout<<"Hello from B::another_func"<<endl;}
};
int main() {

A *temp1 = new A;
//Statement 1
B *b =(B*) temp1;

//Statement 2
//B* b = dynamic_cast<B*>(temp1);


b->another_func();

delete temp1;
return 0;
}

上述程序的输出 -

Hello from B::another_func

我很难理解以下问题-
1) 对于语句 1 我们如何将父对象转换为子对象。从逻辑上讲这应该是不正确的,因为现在我们已经扩大了这个对象的能力(同一个对象现在可以访问子类函数 another_func)。

Java 中的类似代码会产生错误-

“不兼容的类型:A 无法转换为 B
B b = (A)temp;"

现在,如果我们注释语句 1 并取消注释语句 2,语句 2 也会发生类似的事情。

那么,为什么 C++ 允许这样做?

2) 现在,如果我们从两个类中删除 sayhello() 函数,使它们不具有多态关系,则 dynamic_cast 的语句 2 不再有效(因为我们知道 dynamic_cast 可以向下转换多态类)但是 c 风格的转换是语句 1仍然产生相同的输出。
所以我们可以说c-style cast并不是基于类之间的多态关系。
c-style cast 所基于的参数是什么?

最佳答案

假设您切换注释,以便对 C 样式转换进行注释,而对 dynamic_cast 取消注释。此外,将代码修改为:

B* b = dynamic_cast<B*>(temp1);
if(b == nullptr)
cout << "not really a B" << endl;
else
b->another_func();

然后在运行代码时,它会打印出“not really a B”。

如果你看what dynamic_cast does

If the cast is successful, dynamic_cast returns a value of type new_type. If the cast fails and new_type is a pointer type, it returns a null pointer of that type.

所以您使用 dynamic_cast 的版本是未定义的行为,因为您取消引用指针而没有检查转换是否失败。


现在介绍所有使用 C 风格转换的不同版本。 The rules是:

When the C-style cast expression is encountered, the compiler attempts to interpret it as the following cast expressions, in this order:

a) const_cast(expression);

b) static_cast(expression), with extensions: pointer or reference to a derived class is additionally allowed to be cast to pointer or reference to unambiguous base class (and vice versa) even if the base class is inaccessible (that is, this cast ignores the private inheritance specifier). Same applies to casting pointer to member to pointer to member of unambigous non-virtual base;

c) static_cast (with extensions) followed by const_cast;

d) reinterpret_cast(expression);

e) reinterpret_cast followed by const_cast. The first choice that satisfies the requirements of the respective cast operator is selected, even if it cannot be compiled (see example). If the cast can be interpreted in more than one way as static_cast followed by a const_cast, it cannot be compiled.

根据这些规则,您的 C 风格转换等同于

B *b = static_cast<B *>(temp1);

由于 temp1 实际上指向一个 A 对象,因此取消引用结果也是未定义的行为(但出于不同的原因)。


一些一般要点:

  1. C++ 转换是 C 风格转换的细粒度版本。如果你必须投,更喜欢他们。您可以向编译器传达您正在转换的方面。

  2. 您可能应该尽量避免在任何情况下进行强制转换。如果您确实使用dynamic_cast,请检查结果。

关于c++ - C风格的类型转换和动态转换理解困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39694533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com