c string作为返回值之后取不到值得解决方法

今天有一个问题百思不得其解,很头疼,不过最终换一种方式解决了.

#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
继续补上

// 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简单不乱,不混淆。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 34,353评论 18 399
  • 《Extreme Drift Racing》是一款精致的赛车竞速游戏,超多种超级赛车可供选择,操作上模拟真实赛车,...
    游戏玩家灬阅读 225评论 0 0
  • 首先给多态下个定义: 对于面向对象而已,多态分为编译时多态和运行时多态。其中编辑时多态是静态的,主要是指方法的重载...
    Rreply阅读 472评论 0 0
  • 读东野圭吾的《解忧杂货店》后才拿出他的另一本书《白夜行》来读,虽然很厚,但也不是问题,只用了两三天就看完了。 与上...
    雕虫小冀阅读 430评论 0 1
  • 每个人都渴望爱,每个人都渴望被看见。人生是一场自证预言的旅程。作为最爱你们的女人,在敲打给你们情书时,内心充满了虔...
    浮沉浮沉阅读 210评论 0 0

友情链接更多精彩内容