문제

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

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 is occurring with the 4th line (output << "Recipient:...). I'm receiving the error "no operator "<<" matches these operands". However, line 5 is fine.

I'm guessing this has to do with the data type being a string for the package name. Any ideas?

도움이 되었습니까?

해결책

You must be including a wrong string header. <string.h> and <string> are two completely different standard headers.

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

That's for functions of C-style null-terminated char arrays (like strcpy, strcmp etc). cstring reference

#include <string>

That's for std::string. string reference

다른 팁

You are likely missing #include <string>.

Try declaring operator<< as a friend in your class declaration:

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, excepting different case. This wreaks havoc with search and analysis tools. Also, typos can have some fun side-effects too.

use this to output the string..

output << "Recipient: " << package.name.c_str() << endl;

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