2012-08-10 230 views
0

编辑:这是固定的在C++中使用字符串arg的全局函数

我想创建一个具有字符串数据类型的单个参数的全局函数。但是我无法让它工作。以下是我有:

//////// 
//Func.h 

#include <string> 

#ifndef Func_H 
#define Func_H 

void testFunc(string arg1); 

#endif 

//////// 
// Func.cpp 

#include <iostream> 
#include <string> 
#include "Func.h" 
using namespace std; 

void testFunc(string arg1) 
{ 
    cout << arg1; 
} 

时要传递的参数是一个字符串,这是不行的,但如果我的说法整数或字符或其他任何东西(即没有包含任何文件工作),那么它工作正常。

基本上,我想要做的是在自己的.cpp文件中有几个函数,并且能够在Main.cpp中使用它们。我的第一个想法是在头文件中声明原型函数,并将头文件包含在我的Main.cpp中以使用它们。如果你能想到更好的方法,请告诉我。我对C++并不是很有经验,所以我总是乐于改进做事方式。

+4

Erm,'std :: string'。 – 2012-08-10 02:39:39

+0

这是令人尴尬的......无论如何感谢! – ojbway 2012-08-10 02:41:32

回答

1

你忘了命名空间!在函数头中声明功能

using namespace std; 
void testFunc(string arg1); 

,或者你应该写

void testFunc(std::string arg1); 

void testFunc(std::string &arg1); // pointer to string object 

,或者如果你的作用不会改变对象

void testFunc(const std::string &arg1); 

和唐不要忘记Func.cpp,函数在实现中必须与声明具有相同的参数,才能从另一个文件调用它。