将字符串参数传递给另一个字符串
Passing a string argument to another string
我定义了这个类:
class Forum{
std::string title;
Thread* threads[5];
在Forum::Forum的构造函数中,我想传递一个字符串参数来定义title(字符串类型)
Forum::Forum(string *k) {
int i;
std::strcpy(&title.c_str(),k->c_str());
我在这方面有问题。在这段代码中,我得到了一个"作为一元'&'操作数所需的左值"错误。如果我擦除'&'我得到错误"从'const char*'到'char*'的无效转换[-fpermission]"。
有什么想法吗?我将如何用strcpy(或者用另一个方法)将参数传递给字符串类型,以避免上述错误?
除非您希望省略标题,否则我建议您传递const
引用而不是指针:
Forum::Forum(const string& k)
这使得必须提供名称更加明确,并且还允许将字符串文字作为名称进行传递:
Forum f("Main Forum");
然后,要复制std::string
,只需分配它或使用它的复制构造函数。strcpy
仅适用于C样式的char*
字符串。在这种情况下,使用成员初始值设定项:
Forum::Forum(const string& k):
title(k)
{
}
您不需要使用strcpy
,因为这将不起的作用
使用字符串分配运算符
即
Forum::Forum(string *k) {
title = *k;
}
或者更好的
Forum::Forum(const string& k) {
title = k;
}
或者初始化列表
Forum::Forum(const string& k) : title(k) { }
后者是最好的
您肯定应该了解更多关于标准库的信息。在C++中,您可以将一个std::string
分配给另一个,而不会干扰指针和strcpy
。
Forum::Forum(const std::string& k) {
// int i; you aran't using this anywhere, so why declare it?
// as pointed out by @EdHeal, this-> is not necessary here
/*this->*/ title = k;
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 使用另一个字符串从字符串中删除空格
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何在使用 getch 后在另一个字符串的末尾连接一个字符串
- 如何在另一个字符串的x位置插入一个字符串?
- 从 C 字符串构造 std::string 与从另一个 std::string 构造 std::string 不一致
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 在另一个字符串中插入文件扩展名之前的字符串
- 使用C++将一个字符串替换为另一个字符串
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将字符串中的单个单词替换为另一个单词
- 将文本流中一个字符串的所有匹配项替换为另一个字符串
- 无法将字符串用作另一个类的参数
- 另一个字符串文字,UDL 迷宫
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 如何使用循环从另一个字符串创建一个没有空格的新字符串