如何解决带有嵌套类的 C++ 抽象类
我想设计一个带有一些嵌套结构的基类:
class base {
public:
struct PtrType;
virtual bool free(const PtrType& ptr) = 0;
};
强制所有派生类实现自己的PtrType
,例如:
class derived : public base {
public:
struct PtrType {
int a;
};
bool free(const PtrType& ptr) override { return true; }
};
但是这个实现遇到了两个问题:
- 编译器允许派生类嵌套
PtrType
的free
未实现,如果我将基写为
class base {
public:
struct PtrType{
virtual bool free() = 0;
};
virtual bool free(const PtrType& ptr) = 0;
};
- 不允许使用
override
关键字。
我的问题是,我应该如何实现这个基类来强制所有派生类实现某些某些嵌套类?
解决方法
我不确定我是否理解为什么您想要这个,但是要解决 override
问题,您需要使 derived::PtrType
从 base::PtrType
继承,因为它们目前是两个不相关的类。
示例:
class base {
public:
struct PtrType{};
virtual bool free(const PtrType& ptr) = 0;
};
class derived : public base {
public:
struct PtrType : base::PtrType {
int a;
};
bool free(const base::PtrType& ptr) override { return true; }
};
请注意,derived::PtrType
的名称在这里无关紧要。你可以做到:
class derived : public base {
public:
struct Foo : base::PtrType {
int a;
};
bool free(const base::PtrType& ptr) override { return true; }
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。