1

看,我把我的命名空间和函数放在前面,main并且编译成功:

#include <iostream>
#include <exception>
#include <string>
using namespace std;
//==================================================
namespace Bushman{
    void to_lower(char* s)
    // Replace all chars to lower case.
    {
        const int delta = 'a' - 'A';                
        while(*s){
            if(*s >= 'a' && *s <= 'z') *s -= delta;         
            ++s;
        }
    }
}
//==================================================
int main()
// entry point
try{
    namespace B = Bushman; // namespace alias
    void B::to_lower(char* s);  
    char* str = "HELLO, WORLD!";
    B::to_lower(str);   
    printf("%s\n",str);
}
catch(exception& e){
    cerr << e.what() << endl;
    return 1;
}
catch(...){
    cerr << "Unknown exception." << endl;
    return 2;
}

但是,如果我将命名空间和函数放在 之后main,则无法编译:

#include <iostream>
#include <exception>
#include <string>
using namespace std;
//==================================================
int main()
// entry point
try{
    namespace B = Bushman; // namespace alias
    void B::to_lower(char* s);  
    char* str = "HELLO, WORLD!";
    B::to_lower(str);   
    printf("%s\n",str);
}
catch(exception& e){
    cerr << e.what() << endl;
    return 1;
}
catch(...){
    cerr << "Unknown exception." << endl;
    return 2;
}
//==================================================
namespace Bushman{
    void to_lower(char* s)
    // Replace all chars to lower case.
    {
        const int delta = 'a' - 'A';                
        while(*s){
            if(*s >= 'a' && *s <= 'z') *s -= delta;         
            ++s;
        }
    }
}

在第二种情况下为我的命名空间和函数指定声明是如何正确的?

4

2 回答 2

5

您可以在其命名空间内转发声明函数 before main

namespace Bushman
{
  void to_lower(char* s);
}    

int main()
{
  // as before
}
于 2013-07-02T13:11:03.303 回答
0

不太确定你在问什么,但我想这就像普通函数/变量一样。

如果您在之前添加namespace Bushman{}然后在main()之后完全声明它应该可以工作。

于 2013-07-02T13:11:57.157 回答