Search code examples
c++classshared-ptrfriend

Overloading ostream friend operator with shared_ptr vector


I am trying to overload the ostream operator as a friend in a class to build components of a circuit, however it keeps returning the address.

In a series-circuit class in the file "Circuit_classes.h":

friend ostream& operator<< (ostream& os, series_circuit const& myCircuit);

In the file "Circuit_classes.cpp":

ostream& operator<<(ostream& os, series_circuit const& myCircuit){
    os << "Output: " << myCircuit.frequency << endl;
    return os;
}

where frequency is defined in the class header file as 60.

In my main program, "AC Circuits.cpp"

vector<shared_ptr<circuit>> circuit_vector;
circuit_vector.push_back(shared_ptr<circuit>(new series_circuit));
cout << circuit_vector[0] << endl;

Output in the command line when the program is run:

0325E180

Solution

  • cout << circuit_vector[0] << endl;
    

    circuit_vector[0] yields a std::shared_ptr which is what is being printed.

    You must dereference it to get to the object itself.

    cout << *circuit_vector[0] << endl;