简体   繁体   中英

Ostream& operator<< overloading code not working

#include <string>
#include <iostream>

template <typename T>
T max(T a, T b) {
    return a > b ? a : b;
}

class Dummy {
  private:
    std::string name;
    int age;
  public:
    Dummy(int an_age) {age = an_age;}
    bool operator> (Dummy &a) {return age > a.age;}
    std::string toString() const {return "The age is " + age;}
};

std::ostream& operator<<(std::ostream& out, const Dummy& d) {return out<< d.toString();}

int main()
{

  std::cout << max(3, 7) << std::endl;

  std::cout << max(3.0, 7.0) << std::endl;

  std::cout << max<int>(3, 7.0) << std::endl;

  std::cout << max("hello", "hi") << std::endl;

  Dummy d1(10);
  Dummy d2(20);
  std::cout << max(&d1, &d2) << std::endl;

  return 0;
}

I'm pretty new to C++ but not new to programming. I've written the code to play with template and operator overloading in C++.

It took quite a while to make it compile and partially work.

  1. The ostream operator<< is not working properly, only to return the address of the object. I can't figure out the causes.

  2. I managed to make it compile by blind trial and error, so I suspect the code might be broken to some extent. And I may not be aware of what'd be improved.

Your max(&d1,&d2) expression gives you the address , and that is printed out. Your operator overloading is fine.

I assume the line you're talking about is

std::cout << max(&d1, &d2) << std::endl;

The problem is you are passing Dummy * instead of Dummy . That makes max return Dummy * , and since your overloaded operator<< takes (essentially) Dummy , it isn't invoked. If you're trying to pass by reference, you don't need to do anything special on the caller side, just make the function take a reference and the compiler will figure it out.

  1. Don't write your own max , use the standard one instead:

     #include <algorithm> void f() { int a = std::max(8, 4); } 

    The only difference is that the standard max uses operator < by default, just like everything else in the standard library.

  2. Your toString function does something different from what you think it does. It instead returns the sub string of "The age is " starting at the character number age . For example if age is 3, toString will return " age is " . To convert the integer to string you have to use ostringstream :

     std::string toString() const { std::ostringstream s; s << "The age is " << age; return s.str(); } 

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