自从我大约 5 年前转向 C# 以来,我还没有用 C++ 进行过硬核开发。我非常熟悉在 C# 中使用接口(interface)并且一直在使用它们。例如
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++ 中,您无法传递接口(interface),因为当它发现您试图实例化一个未定义其所有方法的类时,您会收到编译错误。
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# 风格界面的正确方法是什么?
最佳答案
当然可以,但是您需要传递引用或指针,而不是按值传递(好吧,迂腐地说,指针也是按值传递的):
void SomeProcedure(IMyInterface& Param)
我认为在这方面它与 C# 类似,只是 C# 默认情况下传递对类的引用,而在 C++ 中,您必须明确说明要通过引用传递它。
按值传递将尝试创建对象的拷贝,而抽象类型(接口(interface))的对象没有意义,因此会出错。
关于c++ - 在 C++ 中正确使用 "interfaces"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14631187/