插入运算符的非成员函数窗体

Non-member-function form for insertion operator

本文关键字:函数 窗体 成员 运算符 插入      更新时间:2023-10-16

我想要一个非类成员重载的 put 运算符,它使用引用参数从汽车对象输出信息。

这是我的代码:

ostream& operator<<(ostream& os, Car& p)
{
         os << "For a car make " << p.get_make() << ", " << p.get_year()<< ", the price is $" << p.get_price()  << endl;
         return os;
}

我收到std::ostream& Car::operator<<(std::ostream&, Car&)' must take exactly one argument错误

我不允许将汽车作为参数吗?

谢谢。

您说要定义一个非成员运算符。但是,您将运算符定义放在类定义中,这使得编译器将其视为成员(此运算符的成员实现必须只有一个参数,因此会出现错误消息)。如果要定义非成员运算符,请将其移出类定义或将其声明为 friend(或两者兼而有之)