我正在尝试调用一个显示结构变量内容的void函数,但是当我调用该函数时出现此错误。
invalid operands of types 'void' and '<unresolved overloaded function type>' to binary 'operator
老实说,我是c ++的新手,我不明白这个错误意味着什么。我该如何解决这个问题?
#include <iostream>
using namespace std;
struct MovieData
{
string title;
string director;
int yearReleased;
int runningTimeInMinutes;
};
void showMovieData(MovieData movie);
int main()
{
MovieData apocalypseNow = {"Apocalypse Now", "Francis Ford Coppola", 1979, 153};
MovieData theWizardOfOz = {"The Wizard of Oz", "Victor Fleming", 1939, 101};
//error occurs here
showMovieData(apocalypseNow) << endl;
showMovieData(theWizardOfOz) << endl;
}
void showMovieData(MovieData movie)
{
cout << "Title: " << movie.title << endl;
cout << "Director: " << movie.director << endl;
cout << "Year Released: " << movie.yearReleased << endl;
cout << "Running Time (in minutes): " << movie.runningTimeInMinutes << endl;
}
答案 0 :(得分:2)
看看这段代码:
showMovieData(apocalypseNow) << endl;
showMovieData(theWizardOfOz) << endl;
此处,showMovieData
是一个返回void
的函数,意味着它不会计算为值。您编写的代码然后尝试将operator <<
应用于不存在的值endl
,这是不可能的,因为您无法将任何运算符应用于void
值。
要解决此问题,请考虑将代码重写为
showMovieData(apocalypseNow);
cout << endl;
showMovieData(theWizardOfOz);
cout << endl;
或者,将showMovieData
替换为可用于显示operator<<
类型对象的全局MovieData
运算符,如下所示:
ostream& operator<<(ostream& out, const MovieData& movie)
{
out << "Title: " << movie.title << endl;
out << "Director: " << movie.director << endl;
out << "Year Released: " << movie.yearReleased << endl;
out << "Running Time (in minutes): " << movie.runningTimeInMinutes << endl;
return out;
}
然后,你可以写
cout << apocalypseNow << endl;
cout << theWizardOfOz << endl;
也就是说,上面的operator<<
定义并不理想,因为它会将endl
插入到流中,刷新内容,但它也应该有效。您可能需要考虑替换内部的endl
operator<<(ostream&, const MovieData&)
'\n'
{{1}}可以避免冲洗。
希望这有帮助!
答案 1 :(得分:1)
您不能在调用endl语句的同一表达式中调用函数“showMovieData”。
你应该重写那两行错误:
showMovieData(apocalypseNow);
cout << endl;
showMovieData(theWizardOfOz);
cout << endl;
编辑 - 打败它,看下面的答案更彻底。