自從我在5年前開始轉向C#以來,我從未在C++中進行過硬核開發。我非常熟悉在C#中使用接口並始終使用它們。例如正確使用C++中的「接口」?
public interface IMyInterface
{
string SomeString { get; set; }
}
public class MyClass : IMyInterface
{
public string SomeString { get; set; }
}
// This procedure is designed to operate off an interface, not a class.
void SomeProcedure(IMyInterface Param)
{
}
這是所有偉大的,因爲你可以實現許多類似的類,並通過他們周圍,而你實際使用不同類的沒有一個人是明智的。但是,在C++中,你不能傳遞接口,因爲當你看到你試圖實例化一個沒有定義好所有方法的類時,你會得到一個編譯錯誤。
class IMyInterface
{
public:
...
// This pure virtual function makes this class abstract.
virtual void IMyInterface::PureVirtualFunction() = 0;
...
}
class MyClass : public IMyInterface
{
public:
...
void IMyInterface::PureVirtualFunction();
...
}
// The problem with this is that you can't declare a function like this in
// C++ since IMyInterface is not instantiateable.
void SomeProcedure(IMyInterface Param)
{
}
那麼,什麼是正確的方式來獲得的C#風格的界面感覺在C++?
不要忘記爲你的'IMyInterface'類添加虛擬析構函數。 –
-1不是真實代碼 –