#define MAX_ParaM_NAME_LEN 32 const char* GetName() { return "Test text"; } int main() { char name[MAX_ParaM_NAME_LEN]; strcpy(name,GetName()); cout << "result: " << name << endl; }
如果我想将结果存储到一个char *(因为框架中的一些功能我只使用char *作为输入),而不使用strcpy(为了实用性和可读性的代码,也学习),怎么可能我做?保持const,这很好:
const char* name; name = GetName();
但我仍然有const.
尝试使用char *:
char* name; name = GetName();
我从“const char *”到“char *”的转换无效.这种转换最好的习惯是什么?
解决方法
如果你使用一个将char *作为输入的函数,并且你有一个const char *(如只读字符串文字),那么你应该提供一个从该const char开始的字符串的深层副本*这样的功能.
你目前拥有的是足够的假设你不能使用std :: string. (如果您可以使用std :: string,并且所有框架函数都使用const char *输入,那么我建议您重构代码以使用std :: string,并将c_str()方法的输出传递给那个字符串类到你的框架函数.)
最后,如果你的一些框架函数需要一个char *,那么你可以随时建立一个小的适配器类:
class Adapter { public: Adapter(const& Adapter) = delete; /*don't try to copy me please*/ Adapter& operator=(const Adapter& ) = delete; /*don't try to copy me please*/ Adapter(const char* s) : m_s(::strdup(s)) { } ~Adapter() /*free memory on destruction*/ { ::free(m_s); /*use free to release strdup memory*/ } operator char*() /*implicit cast to char* */ { return m_s; } private: char* m_s; };
然后对于函数void foo(char * c),可以调用foo(Adapter(“Hello”/ *或任何const char * * /));并且foo可以像嵌入匿名临时的char *一样喜欢它!你甚至可以加强这个类来构造一个char *,在这种情况下,只有一个浅的拷贝的指针被占用(并且析构函数不会删除内存).
原文地址:https://www.jb51.cc/c/116327.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。