2

我正在尝试调用一个显示结构变量内容的 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;
}
4

2 回答 2

2

看看这段代码:

showMovieData(apocalypseNow) << endl;
showMovieData(theWizardOfOz) << endl;

在这里,showMovieData是一个返回的函数void,这意味着它不会计算出一个值。然后,您编写的代码将尝试应用于operator <<不存在的值 and 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'避免冲洗。

希望这可以帮助!

于 2013-10-28T20:15:28.177 回答
1

您不能在调用 endl 语句的同一表达式中调用函数“showMovieData”。

你应该重写这两行给出错误:

showMovieData(apocalypseNow);
cout << endl;
showMovieData(theWizardOfOz);
cout << endl;

编辑-被打败了,请参阅下面更彻底的答案。

于 2013-10-28T20:16:28.757 回答