如何将字符串类型参数传递给c++方法
How to pass string type arguments to c++ methods
我是一个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
引用可能就可以了。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 枚举环境变量的惯用C++14/C++17方法
- 初始化具有非默认构造函数的std::数组项的更好方法