0

编辑:这是固定的

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

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

1 回答 1

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

于 2012-08-10T03:32:46.287 回答