在前向声明类层次结构的shared_ptr之间进行强制转换
Casting between shared_ptr of forward declared class hierarchy
我有一个类只操作shared_ptr到继承层次结构(相当简单,有几个类,说A, B, C
等从单个类Base
继承)。因为我不需要操作A, B, C…它们本身只是向前宣布的。然而,当我试图将shared_ptr<A>
传递给采用shared_ptr<Base>
的方法时,编译器会阻塞,因为编译器不知道a继承自Base。除了static_pointer_cast
或#include
之外,还有其他方法可以作为A类的头吗?如果没有,你会选择哪一个?
编辑:添加一些代码
// in some file: (Base.h)
class Base
{
/*code*/
}
// in another file (A.h)
class A : public Base
{
}
// in my file (impl.cpp)
class A; // forward declaration
void Dummy()
{
std::shared_ptr<A> myPtr;
// we have somewhere: void sillyFunction(shared_ptr<Base> foo)
sillyFunction(myPtr); // does not compile, as no conversion is found.
}
除了static_pointer_castor #包含类A的头文件之外,还有其他方法吗?
。事实上,#include
是正确执行此操作的唯一方法(static_pointer_cast
要么不起作用,要么调用未定义的行为)。也不能在不完整子类和超类之间强制转换普通指针
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- int *ptr = &var 和 int *ptr 之间的区别;*PTR = 和变量?
- (ptr + i)->Func() 和 &ptr[i] 之间有什么区别吗?Func()
- 我如何在void*和boost共享ptr之间切换
- PTR 和 &ptr 之间的区别
- %p 和 cout 和 ptr 之间的C++区别