重载 <<,返回 ostream 会出错。 C++
我遇到了超载 << 的问题操作员。一切都打印并输入正常,但是当我尝试返回 ostream 时,出现此错误:
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
我也已经重载了另一个 <<这个项目中的操作符已经返回了一个 ostream 就好了。以下代码中未使用此运算符。这是代码:
#include "header1.h"
#include <iostream>
using namespace std;
class Car
{
public:
friend class Extras;
friend int main();
friend ostream& operator<< (ostream& os, const Car& in);
Car();
Car(string in_name, int in_year, string in_color, float in_cost);
private:
string name, color;
int year, extr_num;
float cost;
Extras *extr;
};
int main()
{
Car c1;
cout << c1;
return 0;
}
//Default Constructor
Car::Car()
{
name = "TEMP";
color = "BLUE";
year = 0;
cost = 0;
extr = new Extras[3];
extr_num = 0;
}
//Constructor
Car::Car(string in_name, int in_year, string in_color, float in_cost)
{
name = in_name;
color = in_color;
year = in_year;
cost = in_cost;
extr = new Extras[3];
extr_num = 0;
}
//Overloaded << operator for Car class
//This function is the one that fails.
ostream& operator<< (ostream& os, const Car& in)
{
os.precision(2);
os << in.name << ", " << in.year << ", "
<< in.color << ", $"<< in.cost << ", ";
os << "extras include: ";
os << endl;
return os; //Line of code in question
}
另一个标头中的这段代码工作得很好:
ostream& operator<< (ostream& os, Extras const &in)
{
os << in.ex_list;
return os;
}
在返回之前,所有内容都很好地打印到屏幕上。这两个函数对我来说看起来是一样的,有更多 C++ 经验的人可以告诉我吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显示的代码中没有任何内容会导致您描述的问题。 “_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)”错误表明堆在早些时候已损坏,它在您的 return 语句中被检测到,但与您的操作符<< 中的代码没有其他关系。
There's nothing in the shown code that will cause the problem you describe. The "_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)" error is an indication that the heap was corrupted at an earlier point, it's being detected at your return statement but isn't otherwise related to the code in your operator<<
你已经清理了你的堆。它可能与当前运行的代码有任何关系,也可能没有任何关系。尽管我会从使用原始指针开始,但在您决定向我们展示的内容中没有看到任何明显的东西会导致它。
You've hosed your heap. It may or may not have anything to do with the code currently running. Don't see anything immediately apparent in what you've decided to show us that would cause it though I'd start with any use of raw pointers.