字符串到C++中的结构 [英] string to struct in C++

查看:68
本文介绍了字符串到C++中的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串变量

string pr00("")

我想调用方法 fun1

and I want to call the method fun1

fun1(demo *dm)

demo 定义如下

typedef struct 
{
    char pr00[100];
}demo;

调用这个方法是否安全

fun1((demo*)pr00);

谢谢和BR

推荐答案

不,这是不安全的.因为std::string的成员和demo不一样.

No, this is unsafe. Because std::string's members are not the same as demo.

但是你可以定义一个构造函数来将std::string隐式转换为demo类型.

But you can define a constructor to implicitly convert std::string to demo type.

#define MAX_SIZE    100
struct demo 
{    
    demo(const std::string& str)
    {
       memset(pr00, 0, MAX_SIZE);

       if (str.length() < MAX_SIZE)
       {
           strncpy(pr00, str.c_str(), str.length());
           pr00[str.length()] = 0;
       }
    }

    char pr00[MAX_SIZE];
};

现在您可以这样编写代码:

Now you can write code as this:

std::string name("hello world");
demo d(name);

这篇关于字符串到C++中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆