我定义了此类:
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 *'[-fpermissive]的无效转换”。
有什么想法可以避免上述错误,我将如何使用strcpy(或其他方法)将参数传递给字符串类型?
除非您打算省略标题,否则建议您传递const
引用而不是指针:
Forum::Forum(const string& k)
这使得必须提供名称更加明确,并且还允许传递字符串文字作为名称:
Forum f("Main Forum");
然后,要复制std::string
,只需分配它或使用其复制构造函数即可。strcpy
仅适用于C风格的char*
字符串。在这种情况下,请使用成员初始化程序:
Forum::Forum(const string& k):
title(k)
{
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句