在C ++中正确使用“接口”?

时间:2013-01-31 17:01:23

标签: c++ interface coding-style

自从我在大约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#样式界面的正确方法是什么?

4 个答案:

答案 0 :(得分:6)

当然可以,但你需要传递引用或指针,而不是值(迂腐地说,指针也按值传递):

void SomeProcedure(IMyInterface& Param)

我认为在这方面它与C#类似,只是默认情况下C#传递对类的引用,而在C ++中你明确地要说你想通过引用传递它。

传递值将尝试创建对象的副本,抽象类型(接口)的对象没有意义,错误。

答案 1 :(得分:3)

  

但是,在C ++中,你无法通过界面......

您可以将指针引用传递给抽象类,例如:

void SomeProcedure(IMyInterface& Param) { ... }

void SomeProcedure(const IMyInterface& Param) { ... }

答案 2 :(得分:1)

您无法将抽象(接口类)传递给函数的原因是,在创建副本时需要知道对象的大小。

如果所有类的大小相同,这显然不会产生影响,但编译器通常无法知道您的意图是什么,并且实现实际上已经非常普遍基础/接口类中不存在的成员变量[事实上,干净的实现根本不应包含任何数据]。

为了避免知道大小,我们传递指针或引用。现在编译器只需要知道指针的大小 - 这是编译器随时可以知道的。

正如其他答案所说,你传递一个引用,const引用或指向接口的指针,并且可以传入实现对象而无需确切知道它是哪一个。

类似地,如果你想存储同一个基类的一些实现,你可以存储对base的引用或指针,然后让那些引用/指向实现类的实际对象。

答案 3 :(得分:0)

问题中的当前代码:

class IMyInterface
{
public:
   ...
   // This pure virtual function makes this class abstract.
   virtual void IMyInterface::PureVirtualFunction() = 1;
   ... 
}

这只是太多错误

  • IMyInterface::是一种语言扩展,如果它与任何编译器编译(类似的东西用于使用Visual C ++编译)。

  • = 1是语法错误。可能作者的意思是= 0

  • 没有分号的}会导致以后的解析错误。

作为OP问题的原因,诊断后面的代码中的特定事物,正如现有答案到目前为止所做的那样,纯粹是猜测。合理,是的。但是,当OP写道问题是

  

“因为你会收到编译错误”

他或她已经使用上述幻想代码获得了

继续问题的代码:

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)
{
}

应用超长距离迭代收敛心灵感应电路,我猜测代码如下所示:

class IMyInterface
{
public:
   // ...
   virtual void pureVirtualFunction() = 0;
};

class MyClass
    : public virtual IMyInterface
{
public:
   // ...
   void PureVirtualFunction();
};

void SomeProcedure( IMyInterface const& param )
{
}

然后,纠正了无数的语法错误等,只是为了使代码编译,没有明显的问题需要处理:没问题。

免责声明:未受编译人员的影响。此外,既然没有问题,没有讨论。我只是提出编程需要智能,它不能简化为适合机器的规则,因此不要将上述作为绝对规则来遵循。

相关问题