cout 的运算符问题
我有一个简单的包类,它已重载,因此我可以简单地使用 cout << 输出包数据。包名。我还有两种数据类型,名称是字符串,运费是双精度数。
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;
问题出现在第 4 行(输出 <<“收件人:...)。我收到错误“无操作员“<<”匹配这些操作数”。但是,第 5 行没问题。
我猜这与数据类型是包名称的字符串有关。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须包含错误的字符串标头。
和
是两个完全不同的标准标头。这适用于 C 风格的以 null 结尾的 char 数组的函数(如 strcpy、strcmp 等)。 cstring 参考
这是针对
std::string
的。 字符串参考You must be including a wrong string header.
<string.h>
and<string>
are two completely different standard headers.That's for functions of C-style null-terminated char arrays (like
strcpy
,strcmp
etc). cstring referenceThat's for
std::string
. string reference您可能缺少
#include
。You are likely missing
#include <string>
.尝试在类声明中将
operator<<
声明为friend
:顺便说一句,使用具有与数据类型的名称相同,但大小写不同。这对搜索和分析工具造成了严重破坏。此外,拼写错误也会产生一些有趣的副作用。
Try declaring
operator<<
as afriend
in your class declaration: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.
用它来输出字符串..
输出<< “收件人:” << package.name.c_str() <<结束;
use this to output the string..
output << "Recipient: " << package.name.c_str() << endl;