gpt4 book ai didi

c++ - 带有子类的类的纯接口(interface)

转载 作者:行者123 更新时间:2023-11-28 00:42:22 26 4
gpt4 key购买 nike

假设你想创建一个 Derived 类的接口(interface),它看起来像这样:

class Derived : public Base
{
public:
foo();
}

class Base
{
public:
tii();
//many other methods
}

你会如何做界面?如何使 Base::tii 对这个新界面可见(以及其他方法)?

class IDerived
{
public:
virtual foo() = 0;
// should I declare here tii() as a pure virtual function?
// but by doing it now there is ambiguity!
}

什么是好的策略?

新的派生类应该是这样的....

class Derived : public Base, public IDerived
{
//implement the real thing
}

最佳答案

您的示例是倒退的:接口(interface)应该独立于任何具有所有纯虚拟方法的具体类来定义:

class IDerived
{
public:
virtual void foo() = 0;
virtual ~IDerived() {} // don't forget to include a virtual destructor
}

具体类将从接口(interface)公开派生:

class Derived : public Base, public IDerived
{
public:
void foo();
}

如果您希望 IDerived 也声明 Derived 继承自 Base 的方法,您可以显式地使用 Derived通过调用继承的实现来实现该方法:

class Derived : public Base, public IDerived
{
public:
void foo();
void bar() { Base::bar(); }
}

关于c++ - 带有子类的类的纯接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18147170/

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