c++ - Ostream& operator<< 重载代码不起作用

标签 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;
}

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

编译和部分工作花了很长时间。

  1. ostream operator<< 没有正常工作,只能返回对象的地址。我无法找出原因。

  2. 我通过盲试和错误设法使它编译,所以我怀疑代码可能在某种程度上被破坏了。我可能不知道有哪些改进。

最佳答案

您的max(&d1,&d2) 表达式为您提供了地址,并将其打印出来。您的运算符重载没问题。

关于c++ - Ostream& operator<< 重载代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8233647/

相关文章:

wpf - 无法命令将切换按钮绑定(bind)为控件模板

c++ - 如何在 C++ 中重载运算符 ->*

c++ - 使用 SWIG 对 C++ 库进行 Matlab 绑定(bind)

c++ - operator<< 函数的返回值

C++ 通过引用传递指针并分配默认值

c++ - 特征实现使用 clang 和 g++ 给出不同的结果,这是对的吗?

c++ - 如何检索 DirectX 9 的错误字符串

python - Django 模板中的行着色基于 "ifchanged"?

c++ - 为 DiagonalMatrix 对象重载 operator()

c++ - 位域操作中的 operator[] 重载?