【问题标题】:Sending a string variable as a parameter to open a file发送字符串变量作为参数来打开文件
【发布时间】:2016-05-11 03:07:12
【问题描述】:

主要内容:

void HandleAction(const RandomWriter & rw, string choice)
{
   if(choice == "P")
   {
     string fileInput;
     cout << "Change input file: " << endl;
     cin >> fileInput;
     rw.SetFilename(fileInput);
   }
}

在 RandomWriter 类中:

void RandomWriter::SetFilename(string filename)
{
 string text = GetFullFile(filename);
 if (text != "")
{
  fullText = text;
  this->filename = filename;
}

/

为什么当我尝试将 fileInput 作为参数传递给 SetFileName 时出现此错误?

提前谢谢各位!

||=== error: passing 'const RandomWriter' as 'this' argument of 'void RandomWriter::SetFilename(std::string)' discards qualifiers [-fpermissive]|

【问题讨论】:

标签: c++ function file pointers


【解决方案1】:

HandleAction 函数中,您说rw 是对常量 RandomWriter 对象的引用。然后,您尝试调用rw 对象上的成员函数,以尝试修改 常量对象。这当然是不允许的,不能修改常量对象。

所以简单的解决方案是删除参数规范中的const 部分:

void HandleAction(RandomWriter & rw, string choice) { ... }
//                ^^^^^^^^^^^^^^^^^
//         Note: No longer constant

在相关说明中,您可能应该对 strings 使用对常量对象的引用,而不需要一直复制它们。

【讨论】:

    【解决方案2】:

    您的RandomWriter 参数rw 在您的HandleAction() 方法中声明为const,因此是不可变的,并且无法通过您对SetFilename() 的调用来更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 2017-02-02
      相关资源
      最近更新 更多