C ++中字符串arg的全局函数

时间:2012-08-10 02:38:54

标签: c++ visual-c++

编辑:这是固定的

我正在尝试创建一个具有字符串数据类型的单个参数的全局函数。但是我无法让它发挥作用。这就是我所拥有的:

////////
//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;
}

当要传递的参数是一个字符串时,这不起作用,但如果我使参数为整数或char或其他任何东西(不必包含任何文件),那么它可以正常工作。 / p>

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

1 个答案:

答案 0 :(得分: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,函数实现必须与声明具有相同的参数,才能从另一个文件中调用它。