C++ cout 的操作员问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2735194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Operator issues with cout
提问by BSchlinker
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.
我有一个简单的包类,它被重载,所以我可以简单地用 cout << packagename 输出包数据。我也有两种数据类型,名称是字符串,运费是双精度。
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.
问题出现在第 4 行(输出 <<“收件人:...”)。我收到错误“没有运算符“<<”匹配这些操作数”。但是,第 5 行很好。
I'm guessing this has to do with the data type being a string for the package name. Any ideas?
我猜这与作为包名称字符串的数据类型有关。有任何想法吗?
回答by UncleBens
You must be including a wrong string header. <string.h>
and <string>
are two completely different standard headers.
您必须包含错误的字符串标题。<string.h>
并且<string>
是两个完全不同的标准标题。
#include <string.h> //or in C++ <cstring>
That's for functions of C-style null-terminated char arrays (like strcpy
, strcmp
etc). cstring reference
这对于C风格空值终止的字符数组(喜欢的功能strcpy
,strcmp
等等)。字符串引用
#include <string>
That's for std::string
. string reference
那是为了std::string
。字符串引用
回答by sbi
You are likely missing #include <string>
.
你很可能失踪了#include <string>
。
回答by Thomas Matthews
Try declaring operator<<
as a friend
in your class declaration:
尝试在类声明中声明operator<<
为 a 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, excepting different case. This wreaks havoc with search and analysis tools. Also, typos can have some fun side-effects too.
顺便说一句,使用与数据类型同名的变量名是一种非常糟糕的形式,除了大小写不同。这对搜索和分析工具造成了严重破坏。此外,拼写错误也会产生一些有趣的副作用。
回答by Jujjuru
use this to output the string..
用它来输出字符串..
output << "Recipient: " << package.name.c_str() << endl;
输出 << “收件人:” << package.name.c_str() << endl;