抽象或纯方法是虚方法的一个特例(所有抽象或纯方法都是虚拟的)。
我以前的答案是错误的,因为我忽略了构造函数。 C++上的构造函数不是虚拟的,并且不允许在构造函数内调用虚拟(抽象而非抽象方法)。如果你从另一个不是构造函数的方法调用一个非抽象的overrided“parse”,那就没问题。
问题不在于其方法的抽象,它是从构造函数中调用的。
#include <conio>
class Base
{
public:
// a constructor:
Base();
// "virtual and abstract" method:
virtual void parse() = 0;
// "virtual non abstract" method:
virtual void hello();
};
// Error: you cannot call a virtual method from a constructor,
// wheter is abstract or not:
Base::Base()
{
// error:
parse();
// error:
hello();
}
Base::hello()
{
cout << "Hello World\n";
}
class Sub : public Base
{
public:
Sub();
// forgot "virtual" here,
// other languages use "override" instead, here:
virtual void parse();
// another "overriden" methods:
virtual void parse();
};
// right: its important to call the base constructor,
// in this case:
Sub::Sub() : Base()
{
// ...
}
void Sub::parse()
{
// DO stuff
}
int main()
{
Base *MyBaseObject = new Base();
MyObject->parse();
Sub *MyObject = new Sub();
MyObject->parse();
return 0;
}
这是一个解决方法。要调用一个虚拟的方法, 就像是从构造方法中调用,宣布了新的方法,它的构造后立即叫:
#include <conio>
class Base
{
public:
// a constructor:
Base();
// a "postconstructor" or "pseudoconstructor"
virtual void create();
// "virtual and abstract" method:
virtual void parse() = 0;
// "virtual non abstract" method:
virtual void hello();
};
// Error: you cannot call a virtual method from a constructor,
// wheter is abstract or not:
Base::Base()
{
// no virtual methods called here,
// wheter abstract or not
}
// its not a real constructor, just a virtual method:
void Sub::create()
{
// ...
}
Base::hello()
{
cout << "Hello World\n";
}
class Sub : public Base
{
public:
Sub();
virtual void create();
// forgot "virtual" here,
// other languages use "override" instead, here:
virtual void parse();
// another "overriden" methods:
virtual void parse();
};
// right: its important to call the base constructor,
// in this case:
Sub::Sub() : Base()
{
// ...
}
// its not a real constructor, just a virtual method:
void Sub::create() : create()
{
parse();
}
void Sub::parse()
{
// DO stuff
}
int main()
{
// this commented code, wont work
/*
Base *MyBaseObject = new Base();
MyObject->create();
MyObject->parse();
*/
// calling "pseudo-constructor",
// just after real constructor
Sub *MyObject = new Sub(); MyObject->create();
MyObject->parse();
return 0;
}
我的错误道歉。
+1,简而言之,任何类的构造函数中的* this *指向相同的类,而不管它从何处被调用。 –
你为什么不直接在你的回答中使用我的链接? http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.6 – mkb
@Als:尽管他的确是一个正确的陈述,但对于新手来说,这也是相当难以理解的。 ':)' – sbi