简单的程序与结构。得到这个:类型'void'和'<unresolved overloaded =“”function =“”type =“”>'to binary'operator </unresolved>的无效操作数

时间:2013-10-28 20:12:45

标签: c++ iostream

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

2 个答案:

答案 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;

编辑 - 打败它,看下面的答案更彻底。