简书链接:cstring作为返回值之后取不到值得解决方法
文章字数:443,阅读全文大约需要1分钟
今天有一个问题百思不得其解,很头疼,不过最终换一种方式解决了.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| #include "pch.h" #include "Test.cpp" #include <iostream> std::string helloxxx(const char *name) {
std::string temp = "ffff"; std::string new1 = std::string(name); std::string temp2 = new1 + temp;
return temp2;
} int main() {
std::string a = "ff"; std::cout << "Hello World!\n";
const char *temp = Test::hello("fff").c_str(); printf("第一种方式%s \n ",temp);
std::string str = Test::hello("fff"); printf("第二种方式 %s \n",str.c_str()); const char *temp2 = helloxxx("fff").c_str(); printf(temp2); system("pause"); }
|
第二种方式就可以,也就是返回值要定义一个变量接受,不然就去不到值了,这还是比较含义理解的 - - 算了,睡觉
2018年10月22日 01:29:09
唉,c语言始终是让我头疼。
2018年10月22日 20:34:23
继续补上
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| // ConsoleApplicationMethod.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 //
#include "pch.h" //#include "Test.cpp" #include <iostream> //using namespace std;
std::string helloxxx(const char *name) {
std::string temp = "ffff"; std::string new1 = std::string(name); std::string temp2 = new1 + temp;
return temp2;
}
std::string hello(const char *name) {
std::string temp = "ffff"; std::string new1 = std::string(name); std::string temp2 = new1 + temp; return temp2;
}
std::string* hello2(const char *name) {
std::string temp = "ffff"; std::string new1 = std::string(name); std::string *temp2 = new std::string(new1 + temp); return temp2;
}
int main() {
std::string a = "ff"; std::cout << "Hello World!\n";
const char *temp = hello("fff").c_str(); printf("第一种方式将无法显示%s \n ", temp);
std::string str = hello("fff"); printf("第二种方式 %s \n", str.c_str()); const char *temp2 = helloxxx("fff").c_str(); std::string *str3 = hello2("fff"); printf("第三种 new对象返回指针 %s\n ", str3->c_str()); printf("第四种 new对象返回指针 %s\n ", hello2("fff")->c_str()); system("pause"); }
|
打印234结果都正常。
最后的解决方法有2种
1、一种是new一个string返回、
2、或者返回后用一个变量先接收(无法理解,但是好用)。
2019-1-4 12:26:30
虽然这和生命周期有关,但是也有点奇怪,为什么接收一下就ok了,要从汇编级别理解这个问题了?这让我想起c++ 和++c在window和linux的不同了,c之所以操蛋是因为太乱,就内存申请就搞出很多个方式,容易记混淆,而java简单不乱,不混淆。