Is it not necessary to define a class member function?
The following code compiles and runs perfectly,
#include <iostream>
class sam {
public:
void func1();
int func2();
};
int main() {
sam s;
}
Should it not produce a error 开发者_C百科for the lack of class member definition?
If you don't call the member functions, they don't have to be defined. Even if you call them, the compiler won't complain since they could be defined in some other compilation unit. Only the linker will complain. Not defining functions is accepted and common to force an error for undesired behavior (e.g. for preventing copying).
Yes it is perfectly valid to not define a class member function if it is not used. That is also true for non-member functions. A definition is required for virtual functions, though. But pure virtuals can omit definitions if they aren't used.
"Used", btw, does not include refering to the function within sizeof
. In other words, this is still valid:
sizeof (s.func2()); // still not used!
You can define it elsewhere (like another file)
void Sam::func1()
{
// do stuff here
}
From MSDN Linker Error LNK2019
You did define declared it. You just didn't add implementation provided a function prototype. The linker may display a warning if you do not have a function definition (for instance, Borland C++ Builder 5 does not).
精彩评论