开发者

Why can't I call an function in an anonymous namespace from within another function?

I have written this piece of code:

namespace {

void SkipWhiteSpace(const char *&s) {
  if (IsWhiteSpace(*s)) {
    s++;
  }
}

bool IsWhiteSpace(char c) {
  return c == ' ' || c == '\t' || c == '\n';
}

} // namespace

The problem is that the compiler complains that IsWhiteSpace() 开发者_StackOverflowwas not declared in this scope. But why? Sure, the namespace is anonymous but still the functions lie within the same namespace, aren't they?


Perhaps it's because you're defining IsWhiteSpace after SkipWhiteSpace.

Edit:

I successfully compiled the following code:

#include <iostream>

using namespace std;

namespace
{
    void Function2()
    {
        cout << "Hello, world!" << endl;
    }

    void Function1()
    {
        Function2();
    }
}

int main()
{
    Function1();
}

Moving Function1 above Function2 results in the error you mentioned. So, yes, it's because SkipWhiteSpace has no knowledge of IsWhiteSpace. You can solve this by declaring the functions ahead of time and then defining them normally afterwards, like this:

namespace
{
    void Function1();
    void Function2();

    void Function1()
    {
        Function2();
    }

    void Function2()
    {
        cout << "Hello, world!" << endl;
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜