对不起,我确实想要具体。 我期待下面的代码工作,但它并没有和我想不通为什么:/如何将一个指向派生类的指针传递给期望引用基类指针的函数?
#include <cstdio>
#include <cassert>
class UniquePointer
{
public:
void Dispose()
{
delete this;
}
friend void SafeDispose(UniquePointer*& p)
{
if (p != NULL)
{
p->Dispose();
p = NULL;
}
}
protected:
UniquePointer() { }
UniquePointer(const UniquePointer&) { }
virtual ~UniquePointer() { }
};
class Building : public UniquePointer
{
public:
Building()
: mType(0)
{}
void SetBuildingType(int type) { mType = type; }
int GetBuildingType() const { return mType; }
protected:
virtual ~Building() { }
int mType;
};
void Foo()
{
Building* b = new Building();
b->SetBuildingType(5);
int a = b->GetBuildingType();
SafeDispose(b); // error C2664: 'SafeDispose' : cannot convert parameter 1 from 'Building *' to 'UniquePointer *&'
b->Dispose();
}
int main(int argc, char* argv[])
{
Foo();
return 0;
}
请注意,您正在尝试做的事情没有任何“安全”。如果'b'设置为'NULL',那么'b-> Dispose();'会导致行为,就像'b'指向一个被删除的对象一样。 –
@Charles:编辑,等待审查。这个bug不是问题的一部分,是吗? –
此外,由于'Dispose'是公开的,因此不需要'SafeDispose'成为朋友。 –