声明函数 returns 头文件中的字符串

Declare function that returns a string in header file

如何在头文件中声明一个returns字符串的函数,以便其他*.cpp文件可以使用它。

例如,下面的代码无法编译并出现以下错误:

Source.h

#pragma once
#include <string>

string MyFunc();

Source.cpp

#include "stdafx.h"
#include "Source.h"

using namespace std;
string MyFunc()
{
   string str;
   return str;
}

错误

Error   1   error C2146: syntax error : missing ';' before identifier 'MyFunc'  4   1
Error   2   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   4   1
Error   3   error C2872: 'string' : ambiguous symbol    5   1
Error   4   error C2146: syntax error : missing ';' before identifier 'MyFunc'  5   1
Error   5   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   5   1
Error   6   error C2086: 'int string' : redefinition    5   1
Error   7   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   6   1
Error   8   error C2872: 'string' : ambiguous symbol    7   1
Error   9   error C2146: syntax error : missing ';' before identifier 'str' 7   1
Error   10  error C2065: 'str' : undeclared identifier  7   1
Error   11  error C2065: 'str' : undeclared identifier  8   1

如果我用 char* 替换 string,它编译没有错误。

怎么样:

std::string MyFunc();

您需要添加 std:: 前缀,除非您使用命名空间。通常你最好给它加上前缀以避免与你自己的 类.

冲突