简体   繁体   中英

Overloading the << operator and printing out a double pointer

I tried to overload the << operator to print out double pointers, but all im getting is garbage outputs. Here's my code:

    ostream& operator << (ostream& out, const Student& s)
    {
        out << s.height << "/" << s.age;
        return out;
    }

What should i put in the second parameter? Right now it can print out pointers no problem, but when i changed the Student* s to Student** s it is not working.

1.If you overload operator<< like this:

std::ostream& operator << (std::ostream& out, Student& s)
{
    out << s.height << "/" << s.age;
    return out;
}

you can use it like this:

Student stud;
cout << stud;

2.If you overload operator<< like this:

std::ostream& operator << (std::ostream& out, Student* s)
{
    out << s->height << "/" << s->age;
    return out;
}

you can use it like this:

Student *stud = new Student;
cout << stud;
delete stud;

3.If you overload operator<< like this:

std::ostream& operator << (std::ostream& out, Student** s)
{
    out << (*s)->height << "/" << (*s)->age;
    return out;
}

use can use it like this:

Student *stud = new Student;
cout << &stud;
delete stud;

Or you can use all of this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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