c++ - 在 C++ 中正确使用 "interfaces"?

标签 c++ interface coding-style

自从我大约 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/

相关文章:

go - slice of slice 中的接口(interface)转换

c# - 更改为通用接口(interface)对性能的影响

c++ - 带有返回值的 if 语句代码样式

c++ - "cast"指向 C++ 中函数指针的成员函数指针的最简单方法是什么?

c++ - 返回对象值时互斥

c++ - Boost线程析构函数 undefined symbol

c++ - 有没有办法在 Linux 中扫描构​​建的 ARM 库中的函数?

java - 具有接口(interface)的多重继承歧义

haskell - 在 Haskell 中有条件地处理 IO 的惯用方法

html - 好风格 : <br> element in html