[英]Passing a string argument to another string
I have this class defined: 我定义了此类:
class Forum{
std::string title;
Thread* threads[5];
and in the constructor of Forum::Forum I want to pass a string argument to define title(which is of type-string) 在Forum :: Forum的构造函数中,我想传递一个字符串参数来定义title(类型为string)
Forum::Forum(string *k) {
int i;
std::strcpy(&title.c_str(),k->c_str());
I have problems in that.In this code i get an "lvalue required as unary '&' operand" error. 我在那儿有问题。在这段代码中,我收到“一元'&'操作数所需的左值”错误。 If i erase '&' i get the error " invalid conversion from 'const char*' to 'char*' [-fpermissive]".
如果我删除'&',则会收到错误“从'const char *'到'char *'[-fpermissive]的无效转换”。
Any ideas how I will manage to pass the argument with strcpy(or with another method maybe) to a string type avoiding the above errors? 有什么想法可以避免上述错误,我将如何使用strcpy(或其他方法)将参数传递给字符串类型?
Unless you intend to allow the title to be omitted, I would recommend you pass a const
reference instead of a pointer: 除非打算省略标题,否则建议您传递
const
引用而不是指针:
Forum::Forum(const string& k)
This makes it more clear that the name must be provided and also allows passing a string literal as the name: 这使得必须提供名称更加明确,并且还允许传递字符串文字作为名称:
Forum f("Main Forum");
Then, to copy a std::string
, simply assign it or use its copy constructor. 然后,要复制
std::string
,只需分配它或使用其复制构造函数即可。 strcpy
is only for C-style char*
strings. strcpy
仅适用于C样式char*
字符串。 In this case, use a member initializer: 在这种情况下,请使用成员初始化程序:
Forum::Forum(const string& k):
title(k)
{
}
You do not need to use strcpy
- as this will not work 您不需要使用
strcpy
这将无法正常工作
Use the strings assignment operator 使用字符串赋值运算符
ie 即
Forum::Forum(string *k) {
title = *k;
}
Or better still 还是更好
Forum::Forum(const string& k) {
title = k;
}
Or perhaps initialisation lists 也许初始化列表
Forum::Forum(const string& k) : title(k) { }
The latter being the best 后者是最好的
You should definitely learn a bit more about the Standard Library. 您绝对应该了解有关标准库的更多信息。 In C++ you can assign one
std::string
to another without messing with pointers and strcpy
. 在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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.