我想要一个非类成员重载的 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
错误
我不能将 Car 作为参数吗?
谢谢。
最佳答案
您说您想要定义一个非成员 运算符。然而,您将运算符定义放在类定义中,这使得编译器将其视为成员(此运算符的成员实现必须只有一个参数,因此会出现错误消息)。如果你想定义一个非成员运算符,要么将它移到类定义之外,要么将它声明为 friend
(或两者)
关于c++ - 插入运算符的非成员函数形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13486088/