在 C++ 中继承抽象类和类实现;
我希望这是一个简单的问题。
我可以同时继承抽象类及其实现吗?也就是说,可以使以下工作起作用吗?
class A {
virtual void func1() = 0;
}
class B {
void func1() { /* implementation here */ }
}
class C : public A, public B {
}
我尝试了一些变体,并且收到编译错误,抱怨类 C 中未实现的方法。但是,如果我可以完成这项工作,我可以节省大量重复代码。是否可以?
我通过创建一个名为 D 的“复合类”来解决这个问题,它继承自 A & B,但是包含了之前B中包含的实现代码。这使得我的继承模型不太干净,但是它解决了问题,不需要重复代码。而且,正如我在下面的评论中指出的那样,这使我的命名约定变得非常粗糙。
class A {
virtual void func1() = 0;
}
class B {
// Other stuff
}
class D : public A, public B {
void func1() { /* implementation here */ }
}
class C : public D {
}
I hope this is a simple question.
Can I inherit both an abstract class and it's implementation? That is, can the following be made to work?
class A {
virtual void func1() = 0;
}
class B {
void func1() { /* implementation here */ }
}
class C : public A, public B {
}
I've tried a few variations, and am getting compile errors complaining about unimplemented methods in class C. I can save a lot of repeated code if I can make this work, however. Is it possible?
I solved this by creating a "composite class" called D which inherits from A & B, but contains the implementation code previously contained in B. This makes my inheritance model less clean, but it solves the problem without requiring code duplication. And, as I noted in the comments below, it makes my naming conventions pretty gross.
class A {
virtual void func1() = 0;
}
class B {
// Other stuff
}
class D : public A, public B {
void func1() { /* implementation here */ }
}
class C : public D {
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
B 类
不是代码中A 类
的实现。B 类
应该从A 类
继承,并且func1
应该是虚拟的。只有在这种情况下,B 类
才会实现A 类
。然后就不需要同时继承A和B。否则你将得到未实现的纯虚函数
func1
。class B
is not an implementation ofclass A
in your code.Class B
should be inherited fromclass A
andfunc1
should be virtual. Only in that caseclass B
will be implementation ofclass A
. And then there is no need to inherit from both A and B.Otherwise you will get unimplemented pure virtual function
func1
.让 B 从 A 继承。如果不可能,使用虚拟继承也可能有效(我对此并不完全确定)。
Make B inherit from A. If that is not possible, using virtual inheritance might also work (I am not entirely sure about this).
如果您想在 C 类中重用 B 类的代码,请尝试执行以下操作:
If you want to reuse code from B class in C class, try to do something like this:
正如基里尔指出的:你的前提是错误的。
您的示例中的类 B 不继承类 A(需要先声明它才能继承类 A)。
因此,对于编译器来说,B.func1() 与 A.func1() 完全不同。在 C 类中,它期望您提供 A.func1() 的实现,
上面有人发布了类似以下内容的内容:
As Kirill pointed out: Your premise is wrong.
Class B in your example does not inherit class A (it needs to be declared to do that first).
Thus, B.func1() is something entirely different to A.func1() for the compiler. In class C it is expecting you to provide an implementation of A.func1()
Somebody above posted something along the lines of: