簡體   English   中英

如何將字符串類型參數傳遞給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)

我該如何處理字符串參數? 我的嘗試在這里似乎是完全錯誤的。

問候菲利克斯

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引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM