在 Go 中,如果类型具有接口(interface)定义的所有方法,那么它可以分配给该接口(interface)变量,而无需显式继承它。
是否可以在 C/C++ 中模仿此功能?
最佳答案
是的。您可以使用纯抽象类,并使用模板类来包装“实现”抽象类的类型,以便它们扩展抽象类。这是一个准系统示例:
#include <iostream>
// Interface type used in function signatures.
class Iface {
public:
virtual int method() const = 0;
};
// Template wrapper for types implementing Iface
template <typename T>
class IfaceT: public Iface {
public:
explicit IfaceT(T const t):_t(t) {}
virtual int method() const { return _t.method(); }
private:
T const _t;
};
// Type implementing Iface
class Impl {
public:
Impl(int x): _x(x) {}
int method() const { return _x; }
private:
int _x;
};
// Method accepting Iface parameter
void printIface(Iface const &i) {
std::cout << i.method() << std::endl;
}
int main() {
printIface(IfaceT<Impl>(5));
}
关于go - 是否可以在 C/C++ 中模仿 Go 界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8970157/