phi*_*131 1 c++ inheritance casting overloading
在我的代码中,我自然而然地,在没有考虑它的情况下,首先将派生结构类型转换为基础结构以调用重载函数,然后意识到它可能在某些情况下导致问题(尽管我老实说不知道是否哪个).
我的代码如下:
struct Base
{
//some variables
}
struct Derived : Base
{
//some more variables
}
bool func(const Base &base1, const Base &base2)
{
//do some stuff and return true or false
}
bool func(const Base &base, const Derived &derived)
{
if(func(base, (Base)derived))
return true;
else
//do some more stuff and return true or false
}
Run Code Online (Sandbox Code Playgroud)
代码编译,功能按预期工作.
我在SO和其他地方发现了很多关于向上和向下转换的问题,但它们都涉及使用指针而不是直接类型转换为基类.在这个链接中,人直接将类型转换为派生类而不是基类.我发现没有任何问题可以直接解决这个问题,但我可能根本就不知道该寻找什么,所以在这种情况下请指出正确的方向!
我假设(并在线阅读)类型转换涉及创建副本,因此(Base)derived不会简单地返回引用derived,而是使用第一个函数.我可能遇到任何其他缺点或问题吗?