从静态函数返回一个字符串
Returning a string from static function
我有两个文件: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
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 如何检查一个c++字符串中有多少相同的字符/数字
- 获取用C/C++打印的最后一个字符串
- cin >> int 给定一个字符串将 int 赋值为 0
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 使用另一个字符串从字符串中删除空格
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- C++为 void 指针分配一个字符串
- 如何在使用 getch 后在另一个字符串的末尾连接一个字符串
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 如何在另一个字符串的x位置插入一个字符串?
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 在另一个字符串中插入文件扩展名之前的字符串
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- C++自定义流操纵器,用于更改流上的下一个字符串
- 从类返回一个字符串 — 奇怪的行为
- 从我的2d数组中的一列返回的字符串值被压缩为一个字符串(在Mac os上打开Windows txt文件)
- 你能从"volatile const char*"构造一个字符串吗?(不使用`const_cast`