我有一个简单的函数,它接受一个字符串并返回一个字符串,在C中它看起来像;
char* get_string(char c) {
switch(c) {
case 'A': return "some string";
Case 'B': return "some other string";
...
Run Code Online (Sandbox Code Playgroud)
并且它工作正常,但后来我希望我的代码在C++中工作,而C++编译器会抛出一个gamillions"从字符串常量转换为'char*'".我理解这个警告,但我不能100%确定实现该功能的最佳方法是什么,因此它可以快速地在C和C++上工作.这个函数被大量调用,它是一个重要的瓶颈,所以它必须很快.我最好的尝试是;
char* get_string(char c) {
char* str = (char*)malloc(50);
switch(c) {
case 'A':
sprintf(str, "some string");
return str;
Case 'B':
sprintf(str, "some other string");
return str;
...
Run Code Online (Sandbox Code Playgroud)