C++里string如何定义函数?

我这样定义:
string exchange(string x,string y){

}
为什么是错的额?

C++中string类声明函数返回值类型与其他类型相同。如

string methodName(string a, string b)
//methodName为函数名,a,b为参数列表,开头的string为返回值类型。
{
    string comeString = "";
    //...
    return someString;
}

注意事项:

使用string类需要包含头文件#include <string>,他包含在std命名空间中,使用该类型有三种方式

(1)使用std命名空间,即using namespace std;

(2)不使用std命名空间,直接使用using 关键字包含,using std::string;

(3)前两者使用string类时直接使用string,但如果不使用前两者的话,需要在使用时在string前加std::,即std::string来进行变量或函数的声明。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-10
#include<iostream>
#include<string>

std::string exchange(std::string x, std::string y)
{
    return y + x;
}
template<class T>
void  _swap(T& a, T&  b)
{
    T c;
    c = a;
    a = b;
    b = c;
}
int main()
{
    std::string a = "world";
    std::string b = "hello";


    std::cout<< a << "  "<< b<<std::endl;

    _swap<std::string>(a,b);

    std::cout<< a << "  "<< b<<std::endl;
}

程序输出

==================

world  hello
hello  world

==================

你的函数出错了,主要检查三个地方

    是否引入了相关的头文件 比如 #include<string>

    是否用using 引入了命名空间或者在使用的地方使用了命名空间,比如using std::string 或using namespace std 来引入命名空间,或者在代码中使用 std::string

    你是函数是否有正确的返回值,或者函数内部有错误。如果仅仅是声名,那么不要用花括号。

本回答被提问者和网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网