문제

I'm having an issue with overloading the << operator. Everything prints and enters fine, but when I try and return the ostream, I get this error:

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

I've also already overloaded another << operator in this project that has returned an ostream just fine. This operator isn't used in the following code. Here's the code:

#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
}

This bit of code in the other header works perfectly fine:

ostream& operator<< (ostream& os, Extras const &in)
{
    os << in.ex_list;
    return os;
}

Everything prints to the screen fine before the return. And these two functions look the same to me, can someone more experience with C++ tell me otherwise?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top