gpt4 book ai didi

c++ - 我可以使用 static_cast 向下转换吗?

转载 作者:搜寻专家 更新时间:2023-10-30 23:52:51 31 4
gpt4 key购买 nike

我正在学习 C++。我想尝试向下转换接口(interface)类;尽管我知道向下转换可能是由于糟糕的编程设计造成的。

一些站点说“使用 dynamic_cast 来检查向下转换的有效性”。但是,在我的例子中,我不需要检查有效性,因为我可以保证它是从基类到派生类的向下转换。我在下面的示例代码中尝试了 dynamic_cast 和 static_cast。而且效果很好。

当我可以保证 static_cast 是有效的向下转换时,我可以使用它吗?

示例代码:

struct Parent_Interface {
virtual ~Parent_Interface() {};
virtual void print(void) = 0;
};

struct Child : public Parent_Interface {
virtual ~Child() {};
void print(void) override {
std::cout << "Child::print()." << std::endl;
}
};

void StaticDownCastToChild(Parent_Interface& parent_interface) {
auto& child0 = static_cast<Child&>(parent_interface);
std::cout << "StaticDownCastToChild : ";
child0.print();
}

void DynamicDownCastToChild(Parent_Interface& parent_interface) {
auto& child0 = dynamic_cast<Child&>(parent_interface);
std::cout << "DynamicDownCastToChild : ";
child0.print();
}

void test_static_cast_down_cast(void) {
Child c;
StaticDownCastToChild(c);
DynamicDownCastToChild(c);
}

执行 test_static_cast_down_cast() 的输出。

StaticDownCastToChild : Child::print().
DynamicDownCastToChild : Child::print().

最佳答案

Some sites say "use dynamic_cast to check validity of down casting". However, in my case, I don't need to check the validity because I can guarantee it is a down casting from a base class to a derived class.

正确。

Can I use static_cast when I can guarantee it is a valid down casting?

是的。

事实上,您应该,因为它是“免费的”。 dynamic_cast 通常涉及一些运行时开销。

但是,您可能希望将 dynamic_cast 放在 assert 旁边,以备不时之需。请记住,这不会对您的发布版本产生任何影响,但如果出现严重错误,可能会在调试过程中为您提供帮助。在我的职业生涯中,有一些最令人满意的时刻涉及到一个放置得当的 assert 意外触发,从而导致了一个非常快速的错误修复过程;另一种选择可能是数月的痛苦和猜测!

关于c++ - 我可以使用 static_cast 向下转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572340/

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