自从大约 5 年前切换到 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# 风格接口的正确方法是什么?