Ostream&运算符<<重载代码不起作用

Ostream& operator<< overloading code not working

本文关键字:lt 不起作用 代码 重载 运算符 Ostream      更新时间:2023-10-16
#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操作符<<不能正常工作,只能返回对象的地址。我不能找出原因。

  2. 我设法使它通过盲试和错误编译,所以我怀疑代码可能在某种程度上被破坏。我可能没有意识到有什么地方得到了改善。

您的max(&d1,&d2)表达式给出了地址,并将其打印出来。

我猜你说的那行是

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

问题是你通过的是Dummy *而不是Dummy。这使得max返回Dummy *,并且由于您的重载operator<<(基本上)接受Dummy,因此不会调用它。如果你试图通过引用传递,你不需要在调用方做任何特别的事情,只要让函数接受引用,编译器就会找出它。

  1. 不要写自己的max,使用标准的:

    #include <algorithm>
    void f() { int a = std::max(8, 4); }
    
  2. 唯一的区别是标准max默认使用operator <,就像标准库中的其他内容一样。
  3. 您的toString函数所做的事情与您认为的不同。相反,它返回"The age is "的子字符串,从字符号age开始。例如,如果age为3,toString将返回" age is "。要将整数转换为字符串,必须使用ostringstream:

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