#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++ 中的模板和运算符重载。
编译和部分工作花了很长时间。
ostream operator<< 没有正常工作,只能返回对象的地址。我无法找出原因。
我通过盲试和错误设法使它编译,所以我怀疑代码可能在某种程度上被破坏了。我可能不知道有哪些改进。
最佳答案
您的max(&d1,&d2)
表达式为您提供了地址,并将其打印出来。您的运算符重载没问题。
关于c++ - Ostream& operator<< 重载代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8233647/