문제

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(); 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. 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 } ; which is surely illogical .

So , use :

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

If you want to use << operator with class gradeBook1, overload the operator. Instead of using the 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<<gradeBook1;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top