【发布时间】:2012-02-01 16:35:21
【问题描述】:
我通常使用 C# 进行编程,但我正在尝试做一些 C++ 并且在尝试用 C++ 实现接口时有些挣扎。
在 C# 中,我会这样做:
class Base<T>
{
public void DoSomething(T value)
{
// Do something here
}
}
interface IDoubleDoSomething
{
void DoSomething(double value);
}
class Foo : Base<double>, IDoubleDoSomething
{
}
在 C++ 中我是这样实现的:
template <class T>
class Base
{
public:
virtual void DoSomething(T value)
{
// Do something here
}
};
class IDoubleDoSomething
{
public:
virtual void DoSomething(double value) = 0;
};
class Foo : public Base<double>, public IDoubleDoSomething
{
};
问题是我无法实例化 Foo,因为它是抽象的(不实现 DoSomething)。我意识到我可以实现 DoSomething 并在 Base 上调用该方法,但我希望有更好的方法来做到这一点。我有其他类从具有不同数据类型的基类继承,还有其他类从不使用基类的 IDoubleDoSomething 继承。
任何帮助表示赞赏。
【问题讨论】:
-
这有什么不好,还有什么地方可以“更好”?
-
我想“更好”会像 C# 版本一样,其中 'Foo' 从 Base 继承方法并且不需要任何实现。我想从 Foo 中的 Base 实现每个方法并没有什么不好,只是感觉很乱。
-
它很乱,但我从来没有找到更好的方法:(
标签: c# c++ interface multiple-inheritance porting