动态投射智能指针

时间:2012-06-29 20:34:38

标签: c++ pointers dynamic casting

class TcpTahoe是类socket的子类。 看http://www.nsnam.org/doxygen/classns3_1_1_tcp_tahoe.html (我想模拟一个小型网络。)

代码:

Ptr<Socket> ns3TcpSocket;
...
Ptr<TcpTahoe> ptr = dynamic_cast< Ptr<TcpTahoe> >(ns3TcpSocket);
uint32_t ssthresh = ptr->GetSSThresh2();
cout << ssthresh;

所以我现在在运行时,ns3TcpSocket将是一个TcpTahoeSocket。 但我得到一个编译错误。

此致

1 个答案:

答案 0 :(得分:1)

dynamic_cast可用于转换为指针或引用。在您的情况下,Ptr<TcpTahoe>都不是。你应该在这里使用原始指针。我不知道Ptr类,但这些方面的内容应该有效:

Ptr<TcpTahoe> ptr = dynamic_cast<TcpTahoe*>(ns3TcpSocket->GetRawPtr());

(当然,GetRawPtr()已经弥补。如果存在,Ptr operator&的大部分机会都可以解决问题。

哦,请记住dynamic_cast如果无法完成演员,可能会返回NULL。确保你对待这种情况。

相关问题