如何将字符串类型参数传递给c++方法

How to pass string type arguments to c++ methods

本文关键字:c++ 方法 参数传递 类型 字符串      更新时间:2023-10-16

我是一个C++专家,花了几个小时来处理下面的问题。希望有人能启发我。

我有一个cpp文件,内容如下:

test.cpp文件内容

#include <iostream>
#include <exception>
#include <stdlib.h>
#include <string.h>
using std::cin; using std::endl;
using std::string;

string foobar(string bar) {
  return "foo" + bar;
}
int main(int argc, char* argv[])
{
    string bar = "bar";
    System::convCout << "Foobar: " << foobar(bar) << endl;
}

这一个编译并运行良好。现在我想把foobar放入一个外部库:

mylib.h文件内容

string foobar(string bar);

mylib.cpp文件内容

#include <string.h>
using std::cin; using std::endl;
using std::string;
string foobar(string bar) {
  return "foo" + bar;
}

test.cpp文件内容

#include <iostream>
#include <exception>
#include <stdlib.h>
#include "mylib.h"
int main(int argc, char* argv[])
{
    string bar = "bar";
    System::convCout << "Foobar: " << foobar(bar) << endl;
}

我调整了我的Makefile,以便test.cpp编译并链接mylib,但我总是遇到错误:

test.cpp::8 undefined reference to `foobar(std::string)

我必须如何处理字符串参数?我在这里的尝试似乎完全错了。

问候Felix

C++标准库类型std::string位于标头string中。要使用它,必须包含<string>,而不是<string.h>。你的mylib.h应该看起来像

#ifndef MYLIB_H
#define MYLIB_H
#include <string>
std::string foobar(std::string bar);
#endif

并且你的mylib.cpp应该包括它:

#include "mylib.h"
std::string foobar(std::string bar) {
  return "foo" + bar;
}

请注意,可能没有必要按值传递bar。查看您的代码,const引用可能就可以了。