[英]Use of References or Pointers in Interfaces in C++
我正在用 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
ing? 或者,我完全沒有抓住重點?
在此先感謝您的時間!
我對函數和方法參數的經驗法則是使用常量引用 ( const &
) 來僅輸入必需的參數。 對也可以為NULL
輸入參數使用const *
並優先使用指針而不是out
或inout
參數的引用。 這樣,調用者必須將&
用於可能被函數/方法修改的參數,而且它更加明確。 這適用於傳遞類和結構的實例。 對於簡單類型,首選按值傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.