1

在 C++ 类中,我们可以用两种风格中的任何一种来编写我们的成员。我们可以将它们放在命名空间块内,或者我们可以完全限定每个。

有什么理由更喜欢一种风格而不是另一种风格?

头文件如下所示(bar.h):

namespace foo
{
    class Bar
    {
    public:
        Bar();
        int Beans();
    };
}

样式 1 (bar.cpp) -命名空间块内的声明

#include "bar.h"
namespace foo
{
    Bar::Bar()
    {
    }

    int Bar::Beans()
    {
    }
}

样式 2 (bar.cpp) -完全限定声明

#include "bar.h"

foo::Bar::Bar()
{
}

int foo::Bar::Beans()
{
}

所以我的问题,再次,是:有什么理由更喜欢一种风格而不是另一种风格?

4

1 回答 1

0

Here's a possible answer that was posted by James Kanze in answer to another similar question. (edit: note from the comment thread, this only applies to non-member functions).

Prefer the fully qualified form (style 2).

Functions written in this style are explicitly a definition, not a declaration.

That is to say, using Style 2, if you accidentally define a function with incorrect arguments, you'll get a compiler error alerting you to that fact.

Using Style 1, if you define a function with incorrect arguments it will define a different function. It will compile fine, but you'll get a linker error explaining that the method is not defined. This will probably be harder to diagnose than the compiler error resulting from Style 2.

于 2012-05-22T01:21:37.330 回答