Ostream&运算符<<重载代码不起作用
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;
}
我对c++很陌生,但对编程并不陌生。我已经编写了在c++中使用模板和操作符重载的代码。
让它编译和部分工作花了相当长的时间。
ostream操作符<<不能正常工作,只能返回对象的地址。我不能找出原因。
我设法使它通过盲试和错误编译,所以我怀疑代码可能在某种程度上被破坏。我可能没有意识到有什么地方得到了改善。
您的max(&d1,&d2)
表达式给出了地址,并将其打印出来。
我猜你说的那行是
std::cout << max(&d1, &d2) << std::endl;
问题是你通过的是Dummy *
而不是Dummy
。这使得max
返回Dummy *
,并且由于您的重载operator<<
(基本上)接受Dummy
,因此不会调用它。如果你试图通过引用传递,你不需要在调用方做任何特别的事情,只要让函数接受引用,编译器就会找出它。
-
不要写自己的
max
,使用标准的:#include <algorithm> void f() { int a = std::max(8, 4); }
唯一的区别是标准 您的
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(); }
max
默认使用operator <
,就像标准库中的其他内容一样。相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- 我已经完成了<<运算符重载,但它'It’不起作用