C++无法将'const char*'转换为'std :: string*'

Pwn*_*nna 8 c++ string stl

我在下面有这个代码,我在编译时遇到错误:

error: cannot convert 'const char*' to 'std::string*' for argument '1' to 'void sillyFunction(std::string*, int)'

#include <iostream>
#include <string>

using namespace std;
int counter = 0;

void sillyFunction(string * str, int cool=0);

int main(){
    sillyFunction("Cool");
    sillyFunction("Cooler", 1);
    return 0;
}

void sillyFunction(string * str, int cool){
    counter++;
    if (cool){
        for (int i=0; i<counter; i++) cout << *str << endl;
    } else {
        cout << *str << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*n F 13

不要string *仅使用const string &替代品将参数作为尝试

编辑:

std::string并且const char*是不同的类型.在std::string已经具有从字符串文字的转化:(购"Cool"到的实际字符串对象).因此,通过传入字符串文字,"Cool"您在某种意义上传递一个std::string对象,而不是指向一个对象的指针.

我选择使用a的原因const string &主要来自个人编码实践.这样可以最大限度地减少堆栈内存使用量,并且由于传入的是常量字符串文字,因此不需要对参数进行修改.

另外请不要忘记,如果您从string *不再需要更改的内容中进行更改cout:

if (cool){
    for (int i=0; i<counter; i++) cout << str << endl;
} else {
    cout << str << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你详细说明你的答案并解释为什么他应该这样做,我会提出你的答案. (2认同)