简体   繁体   English

C ++错误:“ operator <<”不匹配

[英]C++ error: no match for 'operator<<'

Hello I have a problem with this error I cannot understand what's the problem.. So here is full code: 您好,我有此错误的问题,我无法理解是什么问题。所以这里是完整的代码:

#include <iostream>
#include <string>

using namespace std;

class GradeBook
{
public:
    GradeBook(string name)
    {
        setCourseName(name);
    } // end GradeBook constructor

    void setCourseName(string name)
    {
        courseName = name;
    } // end setCourseName

    string getCourseName()
    {
        return courseName; // return object's courseName
    } // end getCourseName

    void displayMessage()
    {
        cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl;
    } // end displayMessage
private:
    string courseName;
}; // end class GradeBook

int main()
{
    // create two GradeBook objects
    GradeBook gradeBook1("CS101 Introduction to C++ Programming");
    GradeBook gradeBook2("CS102 Data Structures in C++");

    cout << "gradeBook1 created for course: " << gradeBook1.displayMessage();
}

Error part is when I'm trying to print out this line: 错误部分是当我尝试打印此行时:

cout << "gradeBook1 created for course: " << gradeBook1.displayMessage();

If I use it just like gradeBook1.displayMessage(); 如果我像gradeBook1.displayMessage();一样使用它gradeBook1.displayMessage(); it prints the message but if I use it in like I showed it gives me nasty error.. 它会打印消息,但是如果我像显示的那样使用它,则会给我带来讨厌的错误。

Thanks! 谢谢!

displayMessage() is a function who returns void . displayMessage()是一个返回void的函数。 You can't stream this as it's nothing. 您不能流式传输,因为没什么。 Just call it in separate lines. 只需将其单独命名即可。

Change 更改

cout << "gradeBook1 created for course: " << gradeBook1.displayMessage();

to

cout << "gradeBook1 created for course: ";
gradeBook1.displayMessage();

It gets expanded to : 它扩展为:

cout << { cout << "Welcome to the grade book for\\n" << getCourseName() << "!" << endl } ; cout << { cout << "Welcome to the grade book for\\n" << getCourseName() << "!" << endl } ; { cout << "Welcome to the grade book for\\n" << getCourseName() << "!" << endl } ; which is surely illogical . 这肯定是不合逻辑的。

So , use : 因此,使用:

cout << "gradeBook1 created for course: "; cout <<“为课程创建的gradeBook1:”; gradeBook1.displayMessage(); gradeBook1.displayMessage();

If you want to use << operator with class gradeBook1, overload the operator. 如果要对class GradeBook1使用<<运算符,请重载该运算符。 Instead of using the displayMessage(); 而不是使用displayMessage(); method in the class. 类中的方法。

ostream &operator<<(ostream &out)
{
     out<<"Welcome to the grade book for\n" << getCourseName() << "!" << endl;
     return out;
}

The you can call your object using cout, as follows, 您可以使用cout调用对象,如下所示:

cout<<gradeBook1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM