观察以下代码:
class A { public: virtual void Foo() = 0; int Bar; };
class B : public A { public: B( float X ); void Foo(); private: float X; };
class C : public A { public: C( float Y ); void Foo(); private: float Y; };
现在,在某些功能中,假设我这样做:
A*& pToA = pToDerived; // allocated as A* pToDerived = new B( ... );
pToA = pToC; // allocated as A* pToC = new C( ... );
这是有效的吗?如果是这样,即使pToA
是对指针的引用,它是否会导致内存泄漏pToDerived
?
SSCS
假设它Node
有 2 种或多种派生自它的类型。这是我目前正在实现的链表的一个片段,它可能需要多态性才能正常工作,因为它并不意味着是通用的。newnode
是传递给插入函数的参数。
Node* iNode;
for( iNode = mStart; iNode != mEnd; iNode = iNode->Next )
{
if ( iNode->Key == k ) // Replace current node with newnode
{
newnode->Next = iNode->Next;
newnode->Prev = iNode->Prev;
*iNode = *newnode;
delete newnode;
return; // We're done, so we quit.
}
}
// Node doesn't alreay exist, so we add it.
Node*& uglyhack = mEnd;
iNode->Next = newnode;
newnode->Prev = iNode;
uglyhack = newnode;