【发布时间】: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关键字。