'operator>>'的模糊过载

时间:2013-10-03 22:03:08

标签: c++ file overloading

这是我得到的错误:

ambiguous overload for ‘operator>>’ in ‘contestantsInputFile >> contestantName’|

我试图通过引用将文件传递给函数,以便将名称读入名为contestantName的变量。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string contestantName = "";
string contestantName(ifstream &);

int main()
{
    ifstream contestantsInputFile;
    contestantsInputFile.open("contestants_file.txt");    
    contestantName(contestantsInputFile);
}


string contestantName(ifstream &contestantsInputFile)
{
    contestantsInputFile >> contestantName; //this is the line with the error
    return contestantName;
}

1 个答案:

答案 0 :(得分:1)

您尝试从std :: istream中读取函数:

contestantsInputFile >> contestantName; //this is the line with the error

也许这更像你想要的(未经测试):

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string readContestantName(ifstream &); // renamed to be a descriptive verb

int main()
{
    ifstream contestantsInputFile;
    contestantsInputFile.open("contestants_file.txt");    
    std::string contestantName = readContestantName(contestantsInputFile);

    std::cout << "contestant: " << contestantName << "\n";
}


string readContestantName(ifstream &contestantsInputFile)
{
    std::string contestantName; // new variable
    contestantsInputFile >> contestantName; //this is the line with the error
    return contestantName;
}