从静态函数返回一个字符串

Returning a string from static function

本文关键字:一个 字符串 静态函数 返回      更新时间:2023-10-16

我有两个文件: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 "";
}

我的编译器(Visual Studio 2012)是吐出错误的时刻,我有函数getCurrentTimeStamp()返回一个std::string对象。这些错误都指向语法问题,但都不清楚。有人知道为什么会这样吗?

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

错误6错误C2064:项不计算为带0值的函数参数c:usersanthonydocumentscodeconsoleapplication1datetime.cpp 21 1 consoleapplication1

错误1错误C2146:语法错误:标识符之前缺少';''getCurrentTimeStamp' c:usersanthonydocumentscodeconsoleapplication1datetime.h 5 1 consoleapplication1

错误7错误C2146:语法错误:标识符之前缺少';''getCurrentTimeStamp' c:usersanthonydocumentscodeconsoleapplication1datetime.h 5 1 consoleapplication1

错误5 C2371: 'DateTime::getCurrentTimeStamp':重定义;不同的基本type c:usersanthonydocumentscodeconsoleapplication1datetime.cpp 10 1 consoleapplication1

当试图诊断头文件的问题时,尤其是像这样简单的头文件,第一步是尝试看看编译器看到了什么。

#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 "";
    }
http://rextester.com/MODV66772

当我尝试在RexTester的在线Visual Studio上编译这个时,我得到非常不同的错误,告诉我您的stdafx.h不是空的。

如果我稍微修改一下代码:

    //#include "stdafx.h"
    //#include "DateTime.h"
    #include <string>
    class DateTime
    {
    public:
        static std::string getCurrentTimeStamp();
    };
    //#include "DateTime.h"
    #include <ctime>
    #include <chrono>
    #include <iostream>
    #include <string>
    using namespace std;
    string DateTime::getCurrentTimeStamp()
    {
        return "";
    }

现在编译没有错误/警告你报告:http://rextester.com/PXE62490

更改:

  • 包含在头文件中,因为头文件依赖它,
  • 使用std::string代替string

c++编译器是单遍编译器,所以头文件不能知道你打算以后做using namespace std,即使它做了,这是一个可怕的做法,因为std命名空间是密集的。

如果你不能在所有的地方都输入std::,试着在你需要的地方输入using,例如

using std::string;  // string no-longer needs to be std::string
相关文章: