c++ - 插入运算符的非成员函数形式

标签 c++ operator-overloading ostream

我想要一个非类成员重载的 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/

相关文章:

c++ - 如何在指针表示法和数组表示法中循环遍历二维数组

c++ - 避免 `delete[]` 接受隐式指针转换?

c++ - 对运算符 c++ 感到困惑

c++ - 对 `std::ostream& SpyOutput::operator<<<double>(double const&)' 的 undefined reference

c++ - 在 MSVC 中将某些库的目标平台版本设置为 10.x 是否会使程序不兼容在 Windows Vista/7/8 上运行?

c++ - 为什么 not_null 还没有进入 C++ 标准?

类内变量的 C++ 运算符重载

c++ - 清除 cout 缓冲区 (c++)

c++ - C++ 中 unsigned char 的 ostream 运算符重载

c++ - unique_ptr : So I can't reference to a deleted function anymore