在基类中使用抽象期望它是派生类?
采取这个简单的代码:
class A{
public:
virtual void foo() = 0;
void x(){ foo(); }
};
class B: public A{ foo(){ ... } };
main(){
B b;
b.x();
}
我想要的是构建一个抽象类,该类将具有一个函数,该函数将调用一个函数,期望它在派生类中实现
问题是我似乎无法使其工作,编译器说它无法编译,因为它找不到要在基类的 x() 中执行的 foo() 的引用(或类似的东西)。这可以吗?谁能给我举个例子吗?
编辑:似乎当“foo();”时它不起作用位于 A 类(基类)的析构函数内...
这让我很困惑。 =[
编辑2:这有多有趣。我刚刚创建了一个 callfoo(){ foo();现在它编译正常,但是如果我尝试直接从基类 A 的析构函数中调用纯抽象函数,它会给我错误......很奇怪。有人对此有任何想法吗? O_o
对此有什么帮助吗?
谢谢,
乔纳森
更新
它在析构函数之外工作。现在我很困惑。
尝试将“foo()”放入A(基)类的析构函数中,至少对我来说没有编译......
请问有什么帮助吗?
take this simple code:
class A{
public:
virtual void foo() = 0;
void x(){ foo(); }
};
class B: public A{ foo(){ ... } };
main(){
B b;
b.x();
}
What I want is to build an abstract class that will have a function that will call a function expecting it to be implemented in the derived class
The question is that I can't seem to make that work, the compiler says it can't compile because it can't find the reference(or something like that) to the foo() to be executed in x() of the base class. Can this work? Can anyone give me an example of this?
EDIT: It seems that it just doesn't work when the "foo();" is inside the destructor of class A(the base one)...
It just got me confused. =[
EDIT2: how interesting this got. I just created a callfoo(){ foo(); } and now it compiles ok, but if I try to call the pure abstract function directly from within the destructor of Base class A, it gives me errors... weird. Anyone has any idea of this? O_o
any help on this please?
Thanks,
Jonathan
Update
It worked outside the destructor. Now I just got confused.
Try putting the "foo()" inside the destructor of the A(base) class, at least for me is not compiling...
any help plz?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有什么可以阻止您这样做:
至于从析构函数(或构造函数)调用纯虚函数:不要!它会调用未定义的行为。
§10.4/6:
There is nothing preventing you from doing that:
As for calling a pure virtual function from the destructor (or constructor): Don't! It invokes undefined behaviour.
§10.4/6:
它应该与一些语法修改一起工作。
这种技术是完全合法的。
It should work with a few syntactic modifications.
This technique is perfectly legal.
似乎您正在寻找的是 模板方法模式的实现。
您需要使用指针,以利用多态性(从而避免消息... x is not a member of B)
Seems that what you are looking for is an implementation of the Template Method pattern.
You need to use pointers, in order to take advantage of polymorphism (thus avoiding the message ... x is not a member of B)
理论上来说,效果一样好,但您应该向 B 类上的 foo() 添加返回类型
Well in theory that works just as fine, you should though add a return type to foo() on class B