In C++ I can have multiple forward declaration of functions like:
void Func (int);
void Func (int); // another forward declaration, compiles fine
void Func (int) {} // function definition, compiles fine
And yet VC++ 2010 complains when I do the same for member functions (whether or not I include a definition):
class Test {
void Func 开发者_StackOverflow社区(int);
void Func (int); // error C2535 here
void Func (int) {} // error here too
};
I couldn't find anything online about multiple member function forward declarations, whether its legal, illegal, VC++ specific, ect... Is there a way around this? Is it illegal?
Now why would I want to do that? No project in particular, was just playing around with different ways to register functions. In other projects I've had to register functions/classes and used less hack-ish but more tedious methods, and was just trying (for fun) different methods using macros/templates.
Any ideas or thoughts? Specifically on the above question, but also on registering functions/classes.
Thanks in advance for your time ;)
You can't have multiple declarations of a member function inside a class. Your code violates 9.3/2
of the C++ Standard which says
Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates (14.7) appearing outside of the class definition, a member function shall not be redeclared.
There is no need to forward declare member functions. They are visible in the whole class anyway.
As Mark B says, declaring free functions and declaring member functions is treated differently.
Free function declarations can be scattered all around the place, and it would be limiting to require that only one matching declaration be present in a program.
However, you can only define a class in one big chunk of class definition1, so all its member declarations are found in one place. They can't be scattered about your program; consequently, there's no reason for the standard to allow you to write multiple member declarations... so it doesn't:
Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates (14.7) appearing outside of the class definition, a member function shall not be redeclared. [9.3/2]
- Sure, you can include that class definition multiple times in a program, but it must match exactly so, for the purposes of this discussion, it might as well just be a single definition.
精彩评论