gpt4 book ai didi

c++ - 在哪里记录 C++ 中的接口(interface)?

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:05 26 4
gpt4 key购买 nike

我有更多的 Java 背景,因此让我用一个 Java 示例来说明。假设存在以下代码:

interface iFoo {
/* Do foo */
void foo();
/* Do bar */
void bar();
}

class A implements iFoo {
void foo() {};
void bar() {};
}

class B<iFoo> {
iFoo foo;
B() {
foo.foo();
foo.bar();
}
}

//somewhere in the code:
B b = new B<A>();

现在如果我想实现一个可以用作 B 的类型参数的类 C,我知道 C 必须实现 iFoo。因此,我去了那里,按照契约(Contract)设计约定,所有必要的文档都将在那里(我需要实现哪些方法,那里有什么签名和内联文档。

在 C++ 中,它看起来像这样(如果我错了请纠正我):

class A {
public:
void foo();
void bar();
}

template<class T>
class B {
public:
T foo;
B() {
foo.foo();
foo.bar();
}
}

//somewhere in the code:
B *b = new B<A>();

记录 B 对 T 的期望的最佳位置在哪里?或者反过来,如果我有 A 和 B 并且想要实现一个作为类型参数传递给 B 的类 C,我如何找出 B 对 T 的期望?上面当然是一个非常简单的例子,想象一下更大更复杂的类。

最佳答案

在 C++ 中,一个纯抽象接口(interface)类看起来像这样:

struct IFoo
{
virtual void foo() = 0;
virtual void bar() = 0;

virtual ~IFoo() {}
};

然后你像普通类一样继承它

class A : public IFoo
{
public:
void foo();
void bar();
};

关于c++ - 在哪里记录 C++ 中的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19398394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com