复制const char * [英] Copy 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屋!