使用另一个`.cpp`文件中的命名空间定义>>

问题描述 投票:1回答:4

我有这个,我似乎无法正确包含名称空间。

main.cpp

#include <iostream>

int main()
{
    my_space::Print(); // main.cpp:5:5: error: use of undeclared identifier 'my_space'

    return 0;
}

otherclass.cpp

#include <iostream>

namespace  my_space {
    int x, y;

    void Print()
    {
        std::cout << "Hello from namespace my_space." << std::endl;
    }
}

我曾尝试添加一个带有otherclass.hnamespace my_space {};,并在main.cpp中包含#include "otherclass.h",但这也不起作用。

我有这个,我似乎无法正确包含名称空间。 main.cpp #include int main(){my_space :: Print(); // main.cpp:5:5:错误:使用未声明的标识符'...

c++
4个回答
4
投票

您需要从定义

中拆分声明

1
投票

保持您的otherclass.cpp文件不变。看起来不错。


0
投票
在具有main.cpp的编译单元中,未声明名称my_space。因此,编译器会发出错误。

您应该由多个编译单元使用通用声明放置在标头中,并在所有使用标头声明的编译单元中包含此标头。


0
投票
顺便说一句,您应该添加一个有用的提示

using namespace std;

© www.soinside.com 2019 - 2024. All rights reserved.