【问题标题】:Using Ifstream within a function (cannot access private member declared in class)在函数中使用 Ifstream(不能访问类中声明的私有成员)
【发布时间】:2014-02-20 23:53:38
【问题描述】:

我在学习 C++ 时将 ifstream 参数传递给函数时遇到了问题。 不幸的是,仍在学习基础知识,所以我在网上找到解决方案或自己解决它都没有运气。

代码:

#include <iostream>
#include <string>
#include  <fstream>
using namespace std;

int TakefromFile(ifstream gradesinput);
void OutputtoFile();
char GradetoLetter();

void main()
{

    int Studentcount = 0; // Variable that keeps track of the number of students calculated

    ifstream gradesinput; 
    gradesinput.open("grades.txt");

    ofstream gradesoutput; 
    gradesoutput.open("sorted_grades.txt");

    while (gradesinput) // While the file has content to be read
    {
        TakefromFile(gradesinput); //Take data from the line
        OutputtoFile(); //Add it to the output

        Studentcount ++; //Increase studentcount by 1
    }

    gradesinput.close(); //Close both reading and writing files
    gradesoutput.close();
}

int TakefromFile(ifstream gradesinput)
{
    char firstname[20];
    firstname[0] = gradesinput.get();
cout << firstname;
    return 0;
}

void OutputtoFile()
{
}

char GradetoLetter()
{
}

错误出现在主函数“While Loop”中,特别是“TakefromFile”函数 因为“成绩输入”而打电话。调试时错误显示:

'std::basic_ifstream<_Elem,_Traits>::basic_ifstream' : cannot access private member                                           declared in class 'std::basic_ifstream<_Elem,_Traits>'  
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\fstream(827) : see declaration of 'std::basic_ifstream<_Elem,_Traits>::basic_ifstream'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]

感谢任何帮助。如果这是我应该看到的简单的事情,我深表歉意。 谢谢!

【问题讨论】:

    标签: c++ arguments private member ifstream


    【解决方案1】:

    在你的函数中不要通过值传递 ifstream:

    int TakefromFile(ifstream gradesinput)
    

    但通过引用代替

    int TakefromFile(ifstream& gradesinput)
    

    【讨论】:

      【解决方案2】:

      当您将某些内容传递给函数时,实际上是在括号之间创建了您所写内容的副本,然后由函数使用。大多数对象不允许您创建它们自己的副本,因为它根本没有效率,而且通常不是您想要做的。

      & 符号用于获取对象的地址,或者换句话说,引用到它在内存中的位置。您可以创建实际要求参考的函数,如下所示:

      void foo(int& number);
      

      void bar(int &number);
      

      & 符号的位置无关紧要。它实际上不是复制变量,而是告诉函数使用在“内存中”找到的变量。这允许您制作修改您发送给他们的内容的功能。 Ifstreams 在您读取它们时被修改 - 它们的内部光标移动。所以你想通过引用传递它们。

      如果您想通过引用传递某些内容以避免复制大对象,但又不希望用户能够修改它,则可以进行 const 引用。你会在以后的学习中看到很多: void something(const object& obj);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-20
        • 2012-11-15
        • 1970-01-01
        • 1970-01-01
        • 2014-08-23
        相关资源
        最近更新 更多