复制const char * [英] Copy const char*

查看:159
本文介绍了复制const char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从函数接收到一个c字符串作为参数,但我收到的参数将被销毁。



以下是我的意思:

  class MyClass 
{
private:
const char * filename;

public:
void func(const char * _filename);
}

void MyClass :: func(const char * _filename)
{
filename = _filename; //这不工作
}

我想要实现的不是只是将一个存储器地址分配给另一个,但是复制内容。我想要的文件名为const char *而不是char *。



我试图使用strcpy,但它要求目标字符串是非const 。



有办法吗?

解决方案

使用a std :: string 来复制该值,因为您已经在使用C ++。如果你需要一个 const char * ,使用 c_str()

  class MyClass 
{
private:
std :: string filename;
public:
void setFilename(const char * source)
{
filename = std :: string(source);
}

const char * getRawFileName()const
{
return filename.c_str();
}
}


I'm receiving a c-string as a parameter from a function, but the argument I receive is going to be destroyed later. So I want to make a copy of it.

Here's what I mean:

class MyClass
{
private:
 const char *filename;

public:
 void func (const char *_filename);
}

void MyClass::func (const char *_filename)
{
 filename = _filename; //This isn't going to work
}

What I want to achieve is not simply assign one memory address to another but to copy contents. I want to have filename as "const char*" and not as "char*".

I tried to use strcpy but it requires the destination string to be non-const.

Is there a way around? Something without using const_cast on filename?

Thanks.

解决方案

Use a std::string to copy the value, since you are already using C++. If you need a const char* from that, use c_str().

class MyClass
{
private:
    std::string filename;
public:
    void setFilename(const char *source)
    {
        filename = std::string(source);
    }

    const char *getRawFileName() const
    {
        return filename.c_str();
    }
}

这篇关于复制const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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