I have ah as shown below
class A
{
public:
void doSomething()=0;
};
Then i have bh as shown below
#include "a.h"
class b: public A
{
public:
void doSomething();
};
I am just trying to check for syntax errors by trying to compile headers such as g++ -c ah bh
and i get below errror
ah:4: error: initializer specified for non-virtual method 'void A::doSomething()'
What does this error means?
A member function can only be declared abstract ( = 0
) if it is virtual. Add the virtual
keyword to the function declaration in the base class (in class A
).
Prior to C++11, it was also good practice to repeat virtual
in the declaration of the derived class member function, although it's technically not necessary there (as the rule is "once virtual, always virtual").
C++11 introduced the override
keyword which can should used when overriding a virtual member function, to make the code safe against future changes (ie if the base function changes signature, the derived code will fail to compile instead of silently becoming wrong). Whether to also include virtual
when override
is present is up to personal taste/project coding standards. I consider it unnecessary and omit it, but that's just my personal preference.
The problem is exactly what the compiler says it is.
class A
{
public:
virtual void doSomething()=0; // virtual keyword needed
};
这意味着A
做某事不是虚拟的,但你试图让它变成纯粹的虚拟。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.