C++ 从静态函数返回字符串

C++ 从静态函数返回字符串,c++,C++,我有两个文件:DateTime.h和DateTime.cpp,如下所示: DateTime.h class DateTime { public: static string getCurrentTimeStamp(); }; DateTime.cpp #include "stdafx.h" #include "DateTime.h" #include <ctime> #include <chrono> #include <iostream> #inc

我有两个文件:DateTime.h和DateTime.cpp,如下所示:

DateTime.h

class DateTime
{
public:
    static string getCurrentTimeStamp();
};
DateTime.cpp

#include "stdafx.h"
#include "DateTime.h"
#include <ctime>
#include <chrono>
#include <iostream>
#include <string>
using namespace std;

string DateTime::getCurrentTimeStamp()
{
    return "";
}
#包括“stdafx.h”
#包括“DateTime.h”
#包括
#包括
#包括
#包括
使用名称空间std;
字符串DateTime::getCurrentTimeStamp()
{
返回“”;
}
我的编译器(Visual Studio 2012)在使用函数
getCurrentTimeStamp()
返回
std::string
对象的那一刻就抛出了错误。这些错误都指向语法问题,但没有一个是明确的。有人知道为什么会这样吗

更新:这里是(一些)错误

错误6错误C2064:术语的计算结果不是采用0的函数 参数c:\users\anthony\documents\code\consoleapplication1\datetime.cpp 21 1 consoleapplication1

错误1错误C2146:语法错误:缺少“;”前标识符 “getCurrentTimeStamp”c:\users\anthony\documents\code\consoleapplication1\datetime.h 5 1 consoleapplication1

错误7错误C2146:语法错误:缺少“;”前标识符 “getCurrentTimeStamp”c:\users\anthony\documents\code\consoleapplication1\datetime.h 5 1 consoleapplication1

错误5错误C2371:'DateTime::getCurrentTimeStamp':重新定义; 不同基础 类型c:\users\anthony\documents\code\consoleapplication1\datetime.cpp 10 1 consoleapplication1


当试图诊断头文件的问题时,特别是像这样的简单问题,步骤1是尝试查看编译器看到了什么

#include
是一个预处理器指令,因此编译器不会看到它,而是看到您试图包含的文件的预处理输出

因此,您的代码如下所示:

    #include "stdafx.h"

    //#include "DateTime.h"
    class DateTime
    {
    public:
        static string getCurrentTimeStamp();
    };
    //#include "DateTime.h"

    #include <ctime>
    #include <chrono>
    #include <iostream>
    #include <string>
    using namespace std;

    string DateTime::getCurrentTimeStamp()
    {
        return "";
    }
现在编译时不会出现您报告的错误/警告:

这些变化:

  • 包含在头文件中,因为头文件依赖于它
  • 使用
    std::string
    代替
    string
<> > C++编译器是一个单遍编译器,所以头文件不能知道你打算在以后使用命名空间STD 做代码>,即使是这样做,也是一个可怕的实践,因为<代码> STD< /Cord>命名空间密集。 如果你根本无法到处输入
std::
,请尝试使用
你需要的名称,例如

using std::string;  // string no-longer needs to be std::string

Missing#include如果您告诉我们错误是什么,可能会有所帮助?它有更多的错误,这是在您未显示的代码中。我会将
#include
放在“DateTime.h”标题的顶部。使用std::string而不仅仅是string。如果人们认为问题不完整,他们会投反对票。在这种情况下,很难将错误与所显示的代码协调起来。我怀疑那些投了否决票的人是否真的费心去编译这个。也许
DateTime.h
包含在
stdafx.h
中?
using std::string;  // string no-longer needs to be std::string