【问题标题】:getline and passing input streams inside class functions, primary-expression errorgetline 并在类函数中传递输入流,主表达式错误
【发布时间】:2013-09-27 22:50:16
【问题描述】:

我有一个名为 grades.txt 的文件,上面有几行文本和整数,我想将其读入我创建的已定义的名为 Assignment 的类中。

int main()
{
  ifstream input_file("grades.txt");
  Assignment assignment;

  input_file >> assignment;
  return 0;
}

以上是我的主要功能,它将 input_file 读入创建的类分配。

friend istream& operator >> (istream& is, Assignment& assignment)
  { // function to read in data to class variables                                      
    string line;
    getline(*****, line);

    // to be able to operate on strings                                                 
    istringstream iss(line);

    // set values read in from input file.                                              
    iss >> assignment.Assignment_type;
    iss >> assignment.Date;
    iss >> assignment.Max_score;
    iss >> assignment.Actual_score;
    // sometimes Assignment Name will have spaces, have to use getline()                
    getline(is, assignment.Assignment_name);
    return is;
  }

这是一个类函数,它将重载 >> 运算符以读入赋值中的每个变量。这群星星是我遇到的问题,我不知道要传递给它什么。我试过 ifstream 和 ofstream 认为这很简单,但它们返回相同的错误代码

P01.cpp:34:21: error: expected primary-expression before ‘,’ token

【问题讨论】:

  • 您对friend 的使用毫无意义。这显然是一个全局函数,但friends只能在类中声明。这是什么朋友?最好通过让您的 operator>> 简单地使用公共方法来完全避开朋友。
  • 我还假设你在某个地方有一个using std::istream;,否则你需要使用std::istream 而不仅仅是istream
  • 您不应该将您的输入流传递给它吗?如getline(is,line);
  • @Adam 对不起,我应该更详细-这是类Assignment中的调用函数-正确使用朋友,因为值Assignment_type,Date等在私有:块中
  • 不,它没有正确使用,因为这个函数不能是赋值的成员。所以你可以在Assignment中将它声明为友元,但是你必须在类之外定义它,并且没有friend关键字。

标签: c++ token iostream


【解决方案1】:

我猜,您在class Assignment 中定义了这些运算符>>。仅将其声明为朋友,但将定义放在某处:它不是Assignment 的成员。该错误告诉您,运算符>> 在定义为成员时仅采用一个参数(正确的操作数,因为链接是this)。 作为“命名空间”或全局函数,它接受两个参数:链接和权限。

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 2013-09-02
    • 2012-01-03
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    相关资源
    最近更新 更多