Ult*_*nks 1 c++ coding-style interface
我从未在C++中进行过硬核开发,因为我大约在5年前转向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)
{
}
Run Code Online (Sandbox Code Playgroud)
这一切都很棒,因为你可以实现许多类似的类并传递它们,没有人比你更实际使用不同的类更明智.但是,在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)
{
}
Run Code Online (Sandbox Code Playgroud)
那么在C++中感受C#样式接口的正确方法是什么?
当然你可以,但你需要传递引用或指针,而不是值;(好吧,迂腐地说,指针也按值传递):
void SomeProcedure(IMyInterface& Param)
Run Code Online (Sandbox Code Playgroud)
我认为在这方面它与C#类似,只是C#默认传递对类的引用,而在C++中你明确地要说你想通过引用传递它.
传递值将尝试创建对象的副本,抽象类型(接口)的对象没有意义,错误.
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |