Problems with the cout statement

I have a simple package class that is overloaded so I can output the package data simply with cout <package name. I also have two data types: name, which is a string, and double shipping cost.

protected:
    string name;
    string address;
    double weight;
    double shippingcost;

      


ostream &operator<<( ostream &output, const Package &package )
{
    output << "Package Information ---------------";
    output << "Recipient: " << package.name << endl;
    output << "Shipping Cost (including any applicable fees): " << package.shippingcost;

      

The problem occurs with the 4th line (output <<"Receiver: ...). I get the error" no operator "<<matches these operands". However, line 5 is fine.

I'm guessing this is because the datatype is a string for the package name. Any ideas?

+2


a source to share


4 answers


You must include the wrong row header. <string.h>

and <string>

- two completely different standard headers.

#include <string.h> //or in C++ <cstring>

      

This is for the C-style functions with zero completion arrays char (e.g., strcpy

, strcmp

etc.). cstring reference



#include <string>

      

This is for std::string

. string reference

+10


a source


You are probably missing #include <string>

.



+5


a source


Try to declare operator<<

like in your class declaration: friend

struct Package
{
public:
    // Declare {external} function "operator<<" as a friend
    // to give it access to the members.
    friend std::ostream& operator<<(std::ostream&, const Package& p);

protected:
    string name;
    string address;
    double weight;
    double shippingcost;
};

std::ostream&
operator<<(std::ostream& output, const Package& package)
{
    output << "Package Information ---------------";
    output << "Recipient: " << package.name << endl;
    output << "Shipping Cost (including any applicable fees): " << package.shippingcost;
    return output;
}

      

By the way, it is very bad form to use variable names that have the same name as the data type, except in a different case. This is detrimental to search and analytical tools. Moreover, typos can also have some side effects.

+1


a source


use this to output a string.

Output <"Recipient:" <package.name.c_str () <epsI;

-2


a source







All Articles