gpt4 book ai didi

c++ - dynamic_cast 在另一条链上的行为

转载 作者:行者123 更新时间:2023-11-30 01:18:34 27 4
gpt4 key购买 nike

我刚刚在这里读到这个问题 https://stackoverflow.com/a/332086/2689696它告诉动态类型转换

You can use it for more than just casting downwards -- you can cast sideways or even up another chain. The dynamic_cast will seek out the desired object and return it if possible.

那么这到底意味着什么,发生这种情况的限制/条件是什么。

我想这就是声明的意思。转换发生了,我也遇到了明显的段错误。

#include <iostream>
class base
{
public:
virtual void print () = 0;
};

class childa : public base
{
public:
char c1;
virtual void print ()
{
std::cout << "childa\n";
}
void printout()
{
std::cout << "childa out\n";
}
};

class childb : public base
{
public:
int c2;
virtual void print ()
{
std::cout << "childb\n";
}
void printin()
{
std::cout << "childb in\n";
}
void printout()
{
std::cout << "childb out\n";
}
};

int main()
{
base* b = new childa;
b ->print();
dynamic_cast<childa*>(b)->printout();
dynamic_cast<childb*>(b)->printout(); // cast happens here and the output is printed
dynamic_cast<childa*>(b)->c1 = 'a';
dynamic_cast<childb*>(b)->c2 = 2; // segfault here
}

这是我得到的输出,发生了段错误

childa
childa out
childb out

Process returned -1073741819 (0xC0000005) execution time : 5.844 s
Press any key to continue.

编辑:是的,我不检查空值是愚蠢的。但我想更多地了解另一个问题(向上/向下/横向)的评论

最佳答案

你在这里遇到了未定义的行为:

dynamic_cast<childb*>(b)->printout();

转换实际上失败了(返回一个空指针)。您永远不会检查返回值并通过它调用成员函数。那是未定义的行为,任何事情都可能发生。在您的情况下,似乎因为该函数不以任何方式访问 this ,所以即使通过空指针调用它也执行得很好。但这并不能保证。


至于什么是sideways cast(或者向上抛链),需要更复杂的继承层次来论证:

struct base1
{
virtual ~base1() {}
};

struct base2
{
virtual ~base2() {}
};

struct child1 : base1
{};

struct child2 : base2
{};

struct both : child1, child2
{};


int main()
{
child1 *c1 = new both();
static_cast<base1*>(c1); // ok
static_cast<both*>(c1); // ok
static_cast<child2*>(c1); // compile-time error, unrelated types
dynamic_cast<child2*>(c1); // succeeds, because the object is actually of type `both`, i.e. derived from `child2`; cast sideways
static_cast<base2*>(c1); // compile-time error, unrelated types
dynamic_cast<base2*>(c1); // succeeds, because the object is actually of type `both`, i.e. derived from `base2`; cast up another chain

base1 *b1 = new child1();
static_cast<child1*>(b1); // ok
static_cast<both*>(b1); // compiles, but produces UB, as the object is not of correct type
static_cast<base2*>(b1); // compile-time error, unrelated types
dynamic_cast<base2*>(b1); // fails (returns null pointer), because the object is not actually derived from `base2`.
}

关于c++ - dynamic_cast 在另一条链上的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22489333/

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