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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值