简体   繁体   中英

invalid pure specifier (only `= 0' is allowed) before ‘;’ token error with g++

I have this C++ code.

#include <string>
#define IC(E) virtual const E const = NULL; 

struct IDumpable
{
    IC(std::string ToDumpString());
};

class Hello : public IDumpable
{
public:
    const std::string ToDumpString() const {
        std::string a("hello"); return a;
    }
};

int main()
{
    Hello hello;
    hello.ToDumpString();
}

It compiles/runs fine with MSVC, but I got invalid pure specifier (only '= 0' is allowed) before ';' token invalid pure specifier (only '= 0' is allowed) before ';' token error with g++.

What's wrong with it?

GCC uses a built-in __null for NULL (which is a constant integer expression evaluating to zero. __null on GCC satisfies such), so that it can detect special cases and warn about them. Like, accidentally passing NULL to a bool parameter, when it was intended to be passed to a pointer parameter (changes made to a function, forgot to adapt the call side).

Like the error message says, making a virtual function pure requires the exact token sequence = 0 , not some other things ( = 0L or such will fail too).

NULL is a macro that g++ most likely defines to something other than the literal zero, which is perfectly allowed. Use = 0 explicitly to declare abstract functions.

Also I really advise against using a macro such as the one you have to declare pure functions like that. It's just going to make things less clear to future maintainers if they have to look up what it means in order to understand the declaration.

Where did you get the strange habit of using NULL macro in pure specifier?

Using NULL in pure specifier will not work. The syntax for pure specifier is = 0 and only = 0 , nothing else. If it worked for you before, it simply means that the compiler you were using before was defining NULL macro as plain 0 . So, by pure coincidence you could get away with = NULL as pure specifier when using that compiler.

But in general case NULL is not defined as plain 0 and, as I said above, = NULL makes no sense as pure specifier. It will not work. That's exactly what you are observing in your case.

What's wrong is exactly what the error message says: only "= 0" is allowed in the pure virtual function specification, and you're saying instead = NULL . The C++ standard defines NULL as "an implementation-defined C++ null pointer constant" (C++03 §18.1/4). 0 is one such null pointer constant, but NULL is not required to be 0.

It just so happens that MSVC defines NULL to 0, but GCC in fact defines NULL as __null . GCC says that __null is a valid null pointer constant, but __null is not 0, so you cannot use it in the specification of a pure virtual function.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM