抽象或純方法是虛方法的一個特例(所有抽象或純方法都是虛擬的)。
我以前的答案是錯誤的,因爲我忽略了構造函數。 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