在命名空间内声明和定义类

时间:2016-06-15 03:35:01

标签: c++

我在命名空间中定义了命名空间和类,如下所示:

ns.h

namespace Test
{
    class HelloWorld;
};

HelloWorld.h

#include "ns.h"

class Test::HelloWorld
{
public:
    static void print();
};

HelloWorld.cpp

#include "HelloWorld.h"

void Test::HelloWorld::print()
{
    printf("HelloWorld\n");
}

和Test.cpp

#include "ns.h"

using namespace Test;

int _tmain(int argc, _TCHAR* argv[])
{
    HelloWorld::print();

    return 0;
}

我编译并收到了以下错误:error C2027: use of undefined type 'Test::HelloWorld'error C3861: 'print': identifier not found

我想将命名空间和HelloWorld分成不同的文件,以便更简洁,但似乎无法正常工作。我怎么处理这个?

1 个答案:

答案 0 :(得分:1)

ns.h HelloWorld.h 不需要更改

<强> HelloWorld.cpp

#include "HelloWorld.h"

// This was missing, you need it for printf
#include <cstdio>

void Test::HelloWorld::print() {
    printf("HelloWorld\n");
}

<强> Test.cpp的

// No need to include "ns.h" here
//#include "ns.h"

// You need to include "HelloWorld.h" for Test::HelloWorld::print
#include "HelloWorld.h"

// Now you can refer to Test::HelloWorld::print as HelloWorld::print
using namespace Test;

// I am not using Visual Studio so I changed main
// int _tmain(int argc, _TCHAR* argv[])
int main(int argc, char** argv) {
    HelloWorld::print();
    return 0;
}