C++ 错误提示:无法将参数1从const char [8] 转换为char *

#include <iostream>	
using namespace std;

void test(char * p)
{
    cout << p << endl;
}

int main(void)
{
    test("geerniya");
    system("pause");
}

在将字符串当做函数参数传递给函数时,如上所示。编译器会报错C2664 “void test(char *)”: 无法将参数 1 从“const char [12]”转换为“char *”。当把test()函数中的形参改为const char * p 后,错误就没有了。

原因应该是函数的实参与形参类型不匹配, 字符串在内存中是一个常量字符串数组,因此在函数中的形参也应当加上const关键字才行。

改好后的程序如下:

#include <iostream>	
using namespace std;

void test(const char * p)
{
    cout << p << endl;
}

int main(void)
{
    test("geerniya");
    system("pause");
}

猜你喜欢

转载自blog.csdn.net/geerniya/article/details/84669928