如果在我查看时已经回答了这个问题并且找不到答案,我会提前道歉。
注意:这是一个家庭作业,所以如果你觉得回答不舒服,我完全理解。
我有以下内容:
ptr.h:
template<typename T>
class Ptr {
T* address;
size_t* counter;
Ptr(T* address) : address(address), counter(new size_t(1)) { }
Ptr(const Ptr& other) : address(other.address), counter(other.counter)
{
++(*counter);
}
virtual ~Ptr() {
if (0 == --(*counter)) { delete address; delete counter; }
}
Ptr& operator=(const Ptr& right) {
if (address != right.address) {
if (0 == --(*counter)) { delete address; delete counter; }
address = right.address;
counter = right.counter;
++(*counter);
}
return *this;
}
T& operator*() const { TRACE(address); return *address; }
T* operator->() const { TRACE(address); return address; }
T* raw() const { TRACE(addr); return addr; }
};
主.cc:
#include <iostream>
#include "ptr.h"
using std::cout;
using std::endl;
class Base {
public:
Base() { std::cout << "Base()" << std::endl; }
virtual ~Base() { std::cout << "~Base()" << std::endl; }
virtual std::string str() { return "In Base::str()"; }
};
class Derived: public Base {
public:
Derived() { std::cout << "Derived()" << std::endl; }
~Derived() { std::cout << "~Derived()" << std::endl; }
std::string str() { return "In Derived::str()"; }
};
int main() {
Ptr<Base> base(new Base());
Ptr<Derived> derived(new Derived());
Ptr<Base> pbase(0);
Ptr<Derived> pderived(0);
// upcasting can be done like this, but is it the best way?
pbase = *((Ptr<Base>*)(&derived));
cout << pbase->str() << endl; // outputs: "In Derived::str()"
/*
* downcasting should be done using dynamic_casts
* but how can I downcast here?
* what do I know so far:
* 1. just because Derived is a subclass of Base does not mean Ptr<Derived> is a
* subclass of Ptr<Base> so there is no hierarchy between the two so I cannot
* really use dynamic_casts here
* 2. The dynamic_cast I do use is sort of useless no? since pbase is a Ptr<Base>
*/
pderived = *((Ptr<Derived>*)(dynamic_cast<Ptr<Base>*>(&pbase)));
cout << pderived->str() << endl;
return 0;
}
现在,我们的目标是使用 dynamic_cast 来回切换,虽然我发现了许多关于智能指针的有趣花絮,但并没有真正解释它是如何实现的。
我尝试只获取 pbase 的地址字段,然后将 pderived 初始化为具有该地址的新 Ptr,但当然我的引用计数都搞砸了。
我尝试创建一个新的 Ptr 来引用 pderived 的计数器,但后来我无法设置 pderived 的地址字段,所以我也被困在那里。
我告诉你们这些信息是因为: 1. 在在线寻求帮助之前,我想说明我已经为此工作了很长一段时间; 2. 我想让你们知道我已经尝试过什么。
我真的可以在这里使用一些建议。只是如何获得:
pderived = <SOMETHINGSOMETHING>pbase<SOMETHINGSOMETHING>
谢谢!