我想在命名空间范围内定义公共(public)函数(不是在类中 - 这可行) 基本上我想像这样使用它:
std::chrono::milliseconds(16)
我尝试了很多设置,但这是最近的一个:
时间X.h
#ifndef TIMEX_H
#define TIMEX_H
namespace timee{
int now(int z);
}
#endif
TimeX.cpp
#include <chrono>
#include "TimeX.h"
using namespace timee;
int now(int z){return 4;}
main.cpp
#include <iostream>
#include "TimeX.h"
using namespace timee;
int main(int argc, char** argv){
long c = now(2);
std::cout << "c" << c <<std::endl;
return 0;
}
这给了我以下错误:
Main.obj : error LNK2019: unresolved external symbol "int __cdecl timee::now(int)" (?now@timee@@YAHH@Z) referenced in function _SDL_main
这有什么问题?这很困惑。为什么链接器告诉我这是在 _SDL_main
中引用的?我使用 SDL 库,但它与我的功能有什么关系?
与此代码相关的第二个问题。
还有一个额外的问题(如果回答起来不容易,我会开始新的话题)。我正在使用 timee
作为命名空间名称,因为我有一个错误提示 time
名称已在某处使用 Error C2757 .我想它可能嵌套在某个地方。我怎样才能找到它的使用地点以及是否可以使用该名称?我无法想象编译器在弄清楚我想使用什么方面有问题。
最佳答案
你必须像这样定义函数
int timee::now(int z){return 4;}
或者你也可以这样写
#include <chrono>
#include "TimeX.h"
namespace timee
{
int now(int z){return 4;}
}
否则在 cpp 模块中,在全局命名空间中声明(并定义)了另一个具有相同名称的函数
#include <chrono>
#include "TimeX.h"
using namespace timee;
int now(int z){return 4;}
就是这两个定义
int timee::now(int z){return 4;}
int now(int z){return 4;}
定义不同的函数。第一个在命名空间 timee
中声明(并定义)函数而第二个在全局命名空间中声明(并定义)另一个具有相同名称的函数。
至于名字time
然后定义在全局命名空间中,对应C标准函数time
.例如标题 <chrono>
又可以包含标题 <time.h>
名字在哪里 time
已声明。
关于c++ - 定义命名空间作用域函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42775131/