开发者

In .cpp file, defining methods with "class Foo { void method() {} };" instead of "void Foo::method() {}"?

When you have inline definitions of functions in the header file, and you want to move the the function definition bodies out of the header and into a .cpp file, you can't just cut-and-paste the functions as they were defined in the header; you have to convert the syntax from this:

class Foo
{
void method1() { definition(); }
void method2() { definition(); }
void method3() { definition(); }
};

To this:

void Foo::method1() { definition(); }
void Foo::method2() { definition(); }
void Foo::method3() { definition(); }

Edit: Just wanted to point out that what I'm hoping to avoid is having to type the class name in front of every method name. It may seem like a small thing but when you're moving a lot of function definitions out of the header and into the cpp file, it adds up. And when the return type is especially complicated, you have to find where in the line each return type ends and each method name begins.

So my question is, do I have to do it like that second block of code above? What if I did this (is the following standards compliant C++?):

In Foo.h:

class Foo
{
void method1();
void method2();
void method3();
};

In Foo.cpp:

#include "Foo.hpp"    
class Foo
{
void method1()开发者_Python百科 { definition(); }
void method2() { definition(); }
void method3() { definition(); }
};


This will not work: the compiler will see this as you redefining the class. I'm afraid there is no way around this, it's part of the language.

[ps: I know these kinds of jobs are tedious, but we all have to do them at one time or another. If it is that big a job, you could look at writing a script to do it for you, but it really would have to be a big job to justify the effort imho, parsing C++ is not fun]


No. I believe that this violates the One Definition Rule. In any case, it isn't allowed. Remember that #include isn't really seen by the compiler proper. The include is processed before the source is fed to the compiler so what the compiler sees is something like:

#line "foo.cpp" 1
#line "foo.h" 1
class Foo {
    void method1();
    ...
};

#line "foo.cpp" 3
class Foo {
    void method1() {...}
};

So it looks like two conflicting definitions of the same symbol.


yes you have to do it as you show at the top (your original code), I don't think there's a lazy way around it.


You can put the class name in the original definition. That always works. Unfortunately for inlining you will usually no longer really get inlined if it gets put into the cpp file unless it's very very simple or you use a compiler directive.

If it's large enough to want to move into cpp most of the time you don't want it inlined, though.

Another thing is to consider 'helper' classes. Define those elsewhere, which do a lot of the implementation details. Then you can call that in the derived class and it will be inlined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜