【问题标题】:Difference between passing string S and string S[ ] in C++在 C++ 中传递字符串 S 和字符串 S[ ] 之间的区别
【发布时间】:2020-09-07 17:06:11
【问题描述】:
void str(string S[])
{    
    S=S+"jg";
    cout<<S; 
}

在上面的代码中,它抛出了一个错误。我理解,因为我传递了指针 S。但是,当我去掉方括号时,它不会给我一个错误。是什么原因?

【问题讨论】:

  • 一只小猫和一个装满小猫的盒子不是一回事
  • 一个字符串和一个字符串数组在c++中是完全不同的东西...
  • 你是怎么调用str函数的??更新代码

标签: c++ arrays string pointers


【解决方案1】:

如果string 真的是std::string,那么它有一个+ 的重载运算符,将std::string 附加到另一个std::string

字符文字可以衰减为const char *,它可以隐式转换为std::string

因此,如果没有方括号,您将附加两个字符串,并且

S = S + "jg";

真的等价于

S = operator+(S, std::string("jg"));  // Add S and "jg", assign result back to S

相当于

S += "jg";

至于它不能与方括号一起使用的原因是因为S确实是一个指针,它是一个指向string的指针(即string*)。

字符字面量实际上是常量字符数组,并且作为任何数组,它们都会衰减为指向其第一个元素的指针。

这意味着表达式 S + "jg" 正在尝试添加 string*char const* 类型的值,这是不可能的,因此会出现错误。

【讨论】:

  • Noce 理论,但是您是否尝试编译此代码?恐怕它不会编译。
【解决方案2】:

如果我理解正确的话

/*
    accepts array of strings, but you must specify the size also
    other wise function won't know the size of array;

    example: 
        std::string[] arrOfStrings = {"venkat", "chary", "padala"};

        str( arrOfStrings );


        with size parameter;

        str( arrOfStrings, 3 );

*/

void str( std::string s[] ) 
{


}


/*
    accepts std::string 

    example: str( "abcdefg" );

*/

void str( std::string s ) 
{

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-10
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2020-03-10
    相关资源
    最近更新 更多