我在重载 << 运算符时遇到问题。一切都可以打印并正常输入,但是当我尝试返回 ostream 时,出现此错误:
表达式:_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++ 经验的人可以告诉我吗?