Ostream&operator <<重载代码无效

Ter*_* Li 1 c++ templates operator-overloading

#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;
}
Run Code Online (Sandbox Code Playgroud)

我对C++很陌生,但对编程并不陌生.我编写了代码来使用C++中的模板和运算符重载.

它花了很长时间才使它编译并部分工作.

  1. ostream运算符<<无法正常工作,只返回对象的地址.我无法弄清楚原因.

  2. 我设法通过盲目的试验和错误进行编译,所以我怀疑代码可能会在某种程度上被破坏.我可能不知道会有什么改进.

Nik*_*sov 6

你的max(&d1,&d2)表达式为你提供了地址,并打印出来.你的运营商超载很好.