我正在用 C++ 编写一个库,并且想知道使用引用和/或指针代替接口(即使用(抽象)基类作为派生类的占位符)。
问题是,我应该选择两者中的哪一个?我应该更喜欢一个吗?使用对(抽象)基类的引用而不是指针有什么区别吗?
请查看以下代码摘录,并对任何问题发表评论:
#include <iostream>
class Base {
protected:
public:
virtual void Print() const {
std::cout << "Base" << std::endl;
}
};
class Derived : public Base {
protected:
public:
void Print() const override {
std::cout << "Derived" << std::endl;
}
};
class AnotherDerived : public Base {
protected:
public:
void Print() const override {
std::cout << "Another Derived" << std::endl;
}
};
void someFunc( const Base& obj ) {
obj.Print();
}
void anotherFunc( const Base* obj ) {
obj->Print();
}
int main( int argc, char* argv[] ) {
Base baseObj, *basePtr;
Derived derivedObj;
AnotherDerived anotherDerivedObj;
someFunc( derivedObj );
anotherFunc( &derivedObj );
someFunc( anotherDerivedObj );
/* slicing ??? */
baseObj = derivedObj;
/* another slicing ??? */
baseObj = anotherDerivedObj;
/* proper use */
basePtr = &anotherDerivedObj;
someFunc( baseObj );
anotherFunc( basePtr );
return 0;
}
我想,在上面的代码中,我在将子对象复制分配给父对象时进行对象切片。但是,假设我没有做任何对象切片(如前两次调用someFunc
),参考方法会做我打算做的事情吗?dynamic_cast
在决定调用哪个多态函数时,引用和指针方法是否都在内部使用?或者,我完全错过了这里的重点吗?
在此先感谢您的时间!